Laravel 5 isDirty() always returns false
Asked Answered
J

1

12

I want to check if the model has been changed with isDirty method, but always returns false.

This is my code :

 if (!is_null($partnersData)) {
        foreach ($partnersData as $partnerData) {
            $partner = Partner::find($partnerData['partner_id']);
            $partner->update($partnerData);

            if($partner->isDirty()){
                dd('true');
            }
        }
    }
Jaundiced answered 31/3, 2016 at 9:48 Comment(3)
Right after an update the object will not be dirty.Timms
Do you have an updated_at timestamp on your partner table?Dynode
yes, i have updated_atNorthbound
F
24

$model->update() updates and saves the model. Therefore, $model->isDirty() equals false as the model has not been changed since the last executed query (which queries the database to save the model).

Try updating the model like this:

$partner = Partner::find($id);

foreach ($partnerData as $column => $value) {
    if ($column === 'id') continue;

    $partner->$column = $value;
}

if ($partner->isDirty()) {
    // should be dirty now
}

$partner->save(); // $partner will be not-dirty from here
Feeze answered 31/3, 2016 at 9:58 Comment(2)
So, isDirty not checking the state of data in DB but state of data in model that is not saved to the DB yet.Maladjusted
@Maladjusted It's checking against the state of the DB because once it's saved, it's no longer dirty.Epicure

© 2022 - 2024 — McMap. All rights reserved.