Making the Most of Laravel Eloquent Observers: A How-To Guide

Achmad Hadi Kurnia
2 min readAug 28, 2023

--

Photo by Mohammad Rahmani on Unsplash

What are Eloquent Observers?

Eloquent Observers in Laravel are classes that listen to specific Eloquent model events and execute predefined actions when those events are triggered. These events can include creating, updating, deleting, and more. By utilizing Observers, you can separate the logic that responds to events from your actual model, resulting in more organized and maintainable code.

Setting Up an Eloquent Observer:

To create a new Eloquent Observer, follow these steps:

  1. Generate the Observer: In your terminal, run the command php artisan make:observer MyModelObserver, where MyModel is the name of the model you want to observe.
  2. Defining Event Listeners: Open the generated MyModelObserver.php file and define the methods that correspond to the events you want to listen to. For instance, you can have methods like created, updated, and deleted to handle those specific events.
  3. Registering the Observer: Head over to the AppServiceProvider.php file and within the boot method, use the observe method to associate your Observer with the relevant model, like so:
use App\Observers\MyModelObserver;
use App\Models\MyModel;

public function boot()
{
MyModel::observe(MyModelObserver::class);
}

Real-world Use Case:

Let’s say you’re building a blog platform. Whenever a new blog post is created, you might want to automatically generate a slug for the post’s URL based on the title. With an Eloquent Observer, you can listen to the creating event and set the slug attribute accordingly. This keeps your controller or service lean and maintains a separation of concerns.

public function creating(MyModel $model)
{
$model->slug = Str::slug($model->title);
}

Conclusion:

Laravel Eloquent Observers offer an elegant solution to handling model events without cluttering your models themselves. By isolating event-specific logic, you enhance the readability and maintainability of your codebase. Whether it’s automatically generating slugs or performing complex data manipulations, Observers provide a powerful toolset to streamline your development workflow.

--

--