Laravel Eloquent Update Just If Changes Have Been Made

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();

if (count($dirty) > 0)
{
// runs update query
}

return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();

$this->syncOriginal();

$this->fill($attributes);
}

public function syncOriginal()
{
$this->original = $this->attributes;

return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
// changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
// price has changed
}

Laravel: How to verify if model was changed

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

Laravel: Check with Observer if Column was Changed on Update

Edit: Credits to https://stackoverflow.com/a/54307753/2311074 for getOriginal

As tadman already said in the comments, the method isDirty does the trick:

class UserObserver
{

/**
* Listen to the User updating event.
*
* @param \App\User $user
* @return void
*/
public function updating(User $user)
{
if($user->isDirty('email')){
// email has changed
$new_email = $user->email;
$old_email = $user->getOriginal('email');
}
}

}

If you want to know the difference between isDirty and wasChanged, see https://stackoverflow.com/a/49350664/2311074

Laravel how to update value in mysql only if value is changed

Something like this?

$product = Product::find($id);

if ($product->title == $request->title) {
$product->description = $request->description;
} else {
$product->title = $request->title;
}

$product->save();


Related Topics



Leave a reply



Submit