Laravel 10 Model Observers Tutorial Example
Today we are going to discuss Laravel model observers tutorial with examples.
Laravel is a powerful PHP framework that has revolutionized web development with its simplicity and robustness. One of the features that makes Laravel stand out is its support for Model Observers.
Model Observers allow you to attach certain actions to specific events in your Eloquent models, making it easier to perform tasks like auditing, data manipulation, and notifications.
In this tutorial, we will explore the concept of Model Observers in Laravel 10 and demonstrate their usage with a practical example.
Prerequisites
Before diving into this tutorial, you should have a basic understanding of Laravel and its Eloquent ORM. You should also have Laravel 10 installed on your system. If you haven’t done so, you can follow the official Laravel installation guide to set up your environment.
What are Model Observers?
Model Observers are classes that listen for specific Eloquent events and respond to them with custom logic. These events include creating, updating, deleting, and restoring (soft deleting) model instances.
By defining an observer, you can decouple the logic related to these events from your models, leading to a cleaner and more maintainable codebase.
What are the Eloquent model events?
Below is a list of the Eloquent events that observers can listen to:
- retrieved: The event fires when the system retrieves a model from the database.
- creating: The system fires this event just before it saves a new model to the database.
- created: The system fires this event after successfully saving a new model to the database.
- updating: The system fires this event just before updating a model in the database.
- updated: The system fires this event after successfully updating a model in the database.
- saving: The system fires this event just before saving a model (creating or updating) in the database.
- saved: The system fires this event after successfully saving a model (creating or updating) in the database.
- deleting: The system fires this event just before deleting a model from the database.
- deleted: The system fires this event after successfully deleting a model from the database.
- restoring: The system fires this event just before restoring a soft-deleted model.
- restored: The system fires this event after successfully restoring a soft-deleted model.
Creating a Model Observer
To create a Model Observer in Laravel 10, follow these steps:
- Create the Observer Class: Start by generating a new observer class using the
php artisan make:observer
command. ReplaceObserverName
with a meaningful name for your observer.
php artisan make:observer ObserverName
- Defining Event Listeners: Open the newly created observer class in the
app/Observers
directory. Inside the class, you will find various methods corresponding to the Eloquent events you can listen to. For instance, the created method will be triggered when a new model instance is created.
namespace App\Observers; use App\Models\YourModel; class ObserverName { public function created(YourModel $model) { // Your logic here } // Add more event listeners as needed }
3. Registering the Observer: After defining your observer, you need to register it in the boot method of the AppServiceProvider
(if it doesn’t already exist). This will ensure that Laravel knows about your observer and automatically triggers the event listeners when the corresponding events occur.
namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Observers\ObserverName; use App\Models\YourModel; class AppServiceProvider extends ServiceProvider { public function boot() { YourModel::observe(ObserverName::class); } }
Example: Auditing Article Edits
Let’s consider a practical example of using Model Observers to audit article edits in a blog application.
1. Create the Article Model: First, create an Eloquent model for the articles using the following command:
php artisan make:model Article -m
This command will generate the Article model along with a migration file to create the corresponding database table.
2. Add the necessary columns: In the migration file created for the articles table, add two additional columns: last_edited_by
(to store the user ID of the last editor) and last_edited_at
(to store the timestamp of the last edit). Run the migration to update the database.
3. Create the Observer: Now, create an observer called ArticleObserver
using the command mentioned earlier.
php artisan make:observer ArticleObserver
4. Define Event Listeners: In the ArticleObserver
class, define the updating event listener to capture article edits and update the last_edited_by
and last_edited_at
columns.
namespace App\Observers; use App\Models\Article; use Illuminate\Support\Facades\Auth; class ArticleObserver { public function updating(Article $article) { $article->last_edited_by = Auth::id(); $article->last_edited_at = now(); } }
5. Register the Observer: Open the AppServiceProvider
and register the ArticleObserver
in the boot method.
namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Observers\ArticleObserver; use App\Models\Article; class AppServiceProvider extends ServiceProvider { public function boot() { Article::observe(ArticleObserver::class); } }
With this setup, every time an article is updated, the updating method in the ArticleObserver
will be triggered, automatically updating the last_edited_by
and last_edited_at
columns in the database.
Conclusion
In this tutorial, we have explored the concept of Laravel 10 Model Observers and demonstrated their implementation with a practical example. Model Observers help you decouple the logic related to Eloquent events from your models, resulting in cleaner and more maintainable code. By using them, you can easily perform tasks such as auditing, data manipulation, and notifications in response to specific model events.