Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 isDirty() always returns false

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');
            }
        }
    }
like image 734
Вилислав Венков Avatar asked Mar 31 '16 09:03

Вилислав Венков


1 Answers

$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
like image 136
noodles_ftw Avatar answered Sep 23 '22 10:09

noodles_ftw