EXAMINING ATTRIBUTE CHANGES
Feb 15, 2024 Copy Link
Recently I found many developers fall into the trap of using the `isDirty`
, `isClean`
, and `wasChanged`
methods timely. So, lemme explain the difference between these methods:
use App\Models\User;
$user = User::first();
$user->name; // Mahmoud Mohamed
// Before changing the name attribute
$user->isDirty(); // false
$user->isClean(); // true
$user->wasChanged(); // false
$user->name = 'Mahmoud Ramadan';
// After changing the name attribute but, it's not yet persisted to the database
$user->isDirty(); // true
$user->isClean(); // false
$user->wasChanged(); // false
$user->save();
// After saving the new changes to the database
$user->isDirty(); // false
$user->isClean(); // true
$user->wasChanged(); // true
We can say that the methods of
`isDirty`
and`isClean`
work perfectly in retrieving values where these methods determine if any of the model's attributes have been changed since the model was retrieved while`wasChanged`
works well in the process of updating values where determines if any attributes were changed when the model was last saved within the current request cycle.
All the previous methods accept an array of attributes also that you wanna check their change status as Laravel explained 🔬