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
Composer Cannot Download Files
PHP Recursively Unset Array Keys If Match
Getting Cdata Content While Parsing Xml File
Call PHP from Virtual/Custom "Web Server"
Tilde Operator in Regular Expressions
Use Curly Brackets to Structure Code in PHP
Error: File Is Encrypted or Is Not a Database
Updating Product Stock Programmatically in Woocommerce 3
PHP - Returning the Last Line in a File
How to Correct the [Composer\Downloader\Transportexception] Error for Composer
Using Simplexml to Load Remote Url
PHP Warning: Exec() Unable to Fork
Getting Multiple Checkboxes Names/Id's with PHP
Why PHP Variables Start with a $ Sign Symbol
Return PHP Object by Index Number (Not Name)
Laravel Validation: Exists with Additional Column Condition - Custom Validation Rule