- Laravel -

How to Detect Model Attribute Changes in Laravel

|
2 min read
How to Detect Model Attribute Changes in Laravel

Sometimes, it is helpful to know if some values has changed in our model since it was loaded. For example, we might want to check if the is_published attribute/column of an Article model has been set before publishing it.

Laravel offers us some handy methods to track changes in model attributes during a request. Here are the key methods:

  • isDirty: This method checks if any attributes have changed since the model was loaded and before it is saved.
  • isClean: This method checks if no attributes have changed since the model was loaded and before it is saved (Opposite of isDirty.
  • wasChanged: This method checks if any attributes were changed when the model was last saved during the current request.

The isDirty() Method

The isClean() Method

Note: Once the model is saved, both isDirty and isClean will mark the model as NOT DIRTY and CLEAN respectively. SO isDirty() will return false and isClean will return true.

The wasChanged() Method

Conclusion

These methods help you track changes in your models easily, making it simpler to manage and debug your Laravel applications. This is a great way to keep track of changes in your models and ensure that they are always in a valid state.

Your feedback is valuable to me, so if you'd like to see more content like this in the future, please don't hesitate to let me know.

Keep coding, keep exploring, and keep inspiring. 🐼

Written By Anuz Pandey

Anuz Pandey is a multi-disciplinary designer and developer with a passion for creating visually stunning and user-friendly digital experiences. He has been working in the industry for over 5 years. He is currently working as a freelance designer and developer and is available for hire.

Tags

  • laravel
  • php
  • examining-attribute-changes