EXAMINING ATTRIBUTE CHANGES

Feb 15, 2024

Recently, I found that 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 🔬


AI Assistant

Choose AI provider

Text Tools

Make content clear and easy to read

Ask a Question

Get clear answers based on this content

0/500
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.