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
}
// or
if ($post->isDirty(['title', 'author'])) {
// title, author 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->wasChanged()) {
// Some attributes have been modified
// Perform necessary actions
}
// or
if ($post->wasChanged(['title', 'author'])) {
// title, author have been modified
// Perform necessary actions
}