Detect model changes in Laravel using clean methods like wasChanged and isDirty. Improve performance, save conditions, and handle updates precisely.
Need clarity on dirty, clean, and changed states in Laravel models?
Verifying if a model was changed in Laravel involves built-in Eloquent methods like isDirty(), wasChanged() and isClean(). Each helps determine whether an attribute was modified before or after saving.
These checks improve performance, prevent unnecessary database writes and help manage conditional logic inside controllers or services. Ready to see them in action?
Detecting model changes helps you avoid unnecessary database operations and write cleaner logic during updates.
Laravel offers three built-in Eloquent methods isDirty(), wasChanged() and isClean() to track model state before or after saving.
Checks if one or more attributes have been modified but not yet saved.
if ($userA->isDirty()) { // Only save if something was changed
$user->save();
}
Confirms if a model attribute was actually changed during the last save.
$user->name = ‘John’;$user->save();
if ($user->wasChanged(‘name’)) {
// Fire notification or log the update
}
Returns true if the model hasn’t been modified since it was loaded.
if ($userB->isClean()) { // Skip any further logic if no update occurred
}
Also Read: The Popular Sites Built With Laravel
These examples show how to check if specific fields in a Laravel model have changed, with both single and multiple attributes.
$product = Product::find(1);$product->price = 199;
if ($product->isDirty(‘price’)) {
$product->save();
}
$profile = Profile::find(3);$profile->bio = ‘Updated bio’;
$profile->location = ‘Texas’;
if ($profile->isDirty([‘bio’, ‘location’])) {
$profile->save();
}
$article = Article::find(7);$article->title = ‘New SEO Strategy’;
$article->save();
if ($article->wasChanged(‘title’)) {
Log::info(‘Article title was updated.’);
}
Each method serves a different point in the model lifecycle before or after saving to keep your logic clean and efficient.
Laravel makes it simple to detect model changes with isDirty(), wasChanged() and isClean(), giving you full control before and after save operations.
Using the right method at the right time helps reduce overhead, write cleaner code and handle updates more intelligently across your application.
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingLaravel Soft delete keeps your data safe by hiding it instead of deleting it. The row stays in your database, just marked with a deleted_at…
In the ever evolving landscape of web development, Laravel, the most popular PHP frameworks has become a top choice for businesses looking to create high…
Laravel has become the go to PHP framework for businesses in the USA, powering everything from SaaS platforms and eCommerce marketplaces to enterprise grade applications.…
Let’s discuss how our dedicated experts can help.