8

Is there a simple way for the Eloquent save method to check if a row has actually changed? Something like affected_rows for Eloquent?

The only workaround that I found was from Laravel Eloquent update just if changes have been made to do:

$user = Auth::user();

$timestamp = $user->updated_at;

$user->title = $request->input('title');
....

$user->save();

if($timestamp == $user->updated_at){
   // row was not updated.
}

But is this possible to find this out shorter, without the need of a $timestep variable and the check? I don't want to repeat that logic in every controller.

I am looking for something like this:

$user = Auth::user();

$user->title = $request->input('title');
....

if($user->save()){
   // row was updated.
}

But this does not work since $user->save returns true in both cases. Is there another way?

Adam
  • 25,960
  • 22
  • 158
  • 247

3 Answers3

20

First of all instead of:

$user->save

you should rather use:

$user->save();

And to verify if anything was changes in latest Laravel you can use:

if ($user->wasChanged()) {
    // do something
}

but be aware this is as far as I remember in Laravel 5.5

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • 1
    Yes thank you I corrected it. I tried it and it works. One has to call `$user->save()` before `$user->wasChanged()`. – Adam Nov 05 '17 at 11:08
  • 2
    @Adam Yes, you normally run `$user->save()` and you can then run `$user->wasChanged()` to verify if it was changed. If you wanted to verify what was changed you have also method `getChanges()` – Marcin Nabiałek Nov 05 '17 at 11:09
3

You could also skip the save altogether and check if your model ->isDirty(), before calling ->save() at all.

// ...
$user->title = $request->input('title');

if ($user->isDirty()) {
    $user->save();
}

Besides isDirty(), you also have isClean(), and more.

Check out: HasAttributes trait

Robert
  • 5,703
  • 2
  • 31
  • 32
  • 2
    Actually Laravel makes this check itself, before saving it checks if any changes have been done by calling isDirty(), if it returns false, no update is made. – Adham shafik Feb 26 '21 at 13:29
0

Instead use update() to update the records...

$user = Auth::user();
$userUpdated = $user->update($request->all());

//Print number of updated rows...
print($userUpdated);

This will show you the number of affected rows...