Understanding Laravel’s isDirty() and wasChanged() Methods for Attribute Modification Detection

In Laravel, the isDirty() and wasChanged() methods are used to determine if an attribute of a model has been modified.

The isDirty() method checks if any attributes of the model have been changed since it was retrieved from the database or since the last save operation. It returns true if any attributes have been modified, otherwise false. This method does not consider if the model has been saved or not.

Here’s an example usage of isDirty():

$post= Post::find(1);
$post->title = 'How isDirty method works in Laravel';
$post->author = 'Rizwan Sarfraz';

if ($post->isDirty('title')) {
     // The 'title' attribute has been modified
     // Perform necessary actions
}

// or

if ($post->isDirty()) {
     // Some attributes have been modified
     // Perform necessary actions
}

On the other hand, the wasChanged() method specifically checks if a particular attribute has been modified. It takes the name of an attribute as an argument and returns true if the attribute has been changed, otherwise false.

Here’s an example usage of wasChanged():

$post = Post::find(1);
$post->title = 'How wasChanged method works in Laravel';
$post->save();

if ($post->wasChanged('title')) {
     // The 'title' attribute has been modified
     // Perform necessary actions
}

//or

if ($post->hasChanges()) {
     // Some attributes have been modified
     // Perform necessary actions
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.