Prevent Accidental Attribute Changes in Laravel Using isDirty() & wasChanged()
isDirty() → Before Save
Checks if attributes were modified before saving.
$product = Product::find(1);
$product->price = 200;
$product->isDirty('price');
👉 Returns:
true
Real Project Example
if ($product->isDirty('price')) {
// recalculate discount
}
Perfect before calling:
$product->save();
wasChanged() → After Save
Checks what actually changed after saving.
$product->save();
$product->wasChanged('price');
Real Project Example
$product->save();
if ($product->wasChanged('status')) {
dispatch(new SendStatusNotification());
}
Difference Between Them
isDirty()
👉 Checks pending unsaved changes
wasChanged()
👉 Checks saved changes after persistence
Why This Is Useful
It helps you:
- Avoid unnecessary operations
- Prevent duplicate logic
- Trigger actions only when needed
- Optimize model workflows
When to Use Them
Use:
isDirty()→ before savewasChanged()→ after save