Observers In Laravel: A Pragmatic Approach

Joshua Idunnu Paul
4 min readApr 20, 2024

--

Introduction

In Laravel, Observers serve as listeners, waiting for specific events to occur within our application’s models. Understanding their significance and practical application is crucial for ensuring a robust system design. In this comprehensive guide, we’ll dig deep into Laravel Observers, exploring their purpose, creation, utilization, and muting for specific use cases.

What are Observers?

Observers in Laravel act as event listeners attached to Eloquent models. They observe certain actions performed on these models, such as creating, updating, or deleting records, and execute custom logic accordingly. Think of them as watchful guards, ready to spring into action when a relevant event occurs within the model’s lifecycle.

Why Use Observers

The primary use case for Observers lies in separating concerns within our application. Instead of cluttering our model’s methods with additional logic, Observers allow us to maintain clean, focused code by encapsulating event-based behaviour outside the model itself. This promotes better code organization, readability, and maintainability.

Creating An Observer

Using Laravel’s Artisan CLI tool, we can generate an Observer with the following command:

php artisan make:observer UserObserver --model=User

This command generates a new observer named UserObserver specifically designed for the User model.

<?php

namespace App\Observers;

use App\Models\User;

class UserObserver
{
/**
* Handle the User "creating" event.
*
* @param \App\Models\User $user
* @return void
*/
public function creating(User $user)
{
//
}

/**
* Handle the User "created" event.
*
* @param \App\Models\User $user
* @return void
*/
public function created(User $user)
{
//
}

/**
* Handle the User "updating" event.
*
* @param \App\Models\User $user
* @return void
*/
public function updating(User $user)
{
//
}

/**
* Handle the User "updated" event.
*
* @param \App\Models\User $user
* @return void
*/
public function updated(User $user)
{
//
}

/**
* Handle the User "deleting" event.
*
* @param \App\Models\User $user
* @return void
*/
public function deleting(User $user)
{
//
}

/**
* Handle the User "deleted" event.
*
* @param \App\Models\User $user
* @return void
*/
public function deleted(User $user)
{
//
}

/**
* Handle the User "restoring" event.
*
* @param \App\Models\User $user
* @return void
*/
public function restoring(User $user)
{
//
}

/**
* Handle the User "restored" event.
*
* @param \App\Models\User $user
* @return void
*/
public function restored(User $user)
{
//
}
}

Register the observer by invoking the observe method on the model you wish to observe. This typically occurs within the boot() method of the App\Providers\AppServiceProvider class.

<?php

namespace App\Providers;

use App\Models\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
}

Observer Methods

Now, let’s look into some of the methods provided by our observer class and how it can be use in our application.

public function creating(User $user)
{
$user->slug = Str::slug($user->name);
}

When a new user is being created, this method automatically generates a slug for the user’s name using Laravel’s Str::slug() helper function. This ensures that the slug is URL-friendly and can be used for SEO purposes or in routing.

created()

public function created(User $user)
{
Mail::to($user->email)->send(new WelcomeEmail($user));
}

After a new user is successfully created, this method sends a welcome email to the user’s email address using Laravel’s built-in mail system. It utilizes the WelcomeEmail Mailable class to generate and send the email to the user.

updating()

public function updating(User $user)
{
if ($user->isDirty('address')) {
Log::info("User address changed from {$user->getOriginal('address')} to {$user->address}");
}
}

When a user’s information is being updated, this method checks if the email address is being modified. If the address is indeed being changed, it logs an information message indicating the old and new addresses using Laravel’s logging system.

updated()

public function updated(User $user)
{
if ($user->isDirty('status') && $user->status === 'banned') {
Mail::to($user->email)->send(new AccountBannedNotification($user));
}
}

When the user model is updated, we check if the user’s status has been modified and the new status is “banned” using $user->isDirty('status') && $user->status === 'banned'. If the condition is met, we use Laravel’s mail system to send an email notification to the user’s email address ($user->email) using the AccountBannedNotification Mailable class. This notification can include details about the reason for the ban and any further instructions the user needs to follow.

deleting()

public function deleting(User $user)
{
if ($user->articles()->exists()) {
throw new \Exception('Cannot delete user with associated articles');
}
}

Before a user is deleted from the database, this method checks if the user has any associated articles. If the user has articles associated with them, it throws an exception to prevent the user from being deleted, ensuring data integrity and enforcing business rules.

deleted()

public function deleted(User $user)
{
Notification::send(User::administrators()->get(), new UserDeletedNotification($user));
}

When a user, it sends a notification to administrators, informing them about the deletion of the user.

restoring()

public function restoring(User $user)
{
$deletedArticles = $user->articles()->onlyTrashed()->get();

foreach ($deletedArticles as $article) {
$article->restore();
}

}

When a user is being restored from soft deletion, this method retrieves all articles associated with the user that have been soft deleted (onlyTrashed()). It then iterates over these deleted articles and restores each one, bringing them back into the active state.

restored()

public function restored(User $user)
{
Notification::send(User::administrators()->get(), new UserRestoredNotification($user));
}

After a user has been successfully restored from soft deletion, this method sends a notification to the administrators to inform them about the user’s restoration. It utilizes Laravel’s notification system to send the notification to all administrators.

Conclusion

By mastering Laravel Observers, developers can enhance the scalability, maintainability, and flexibility of their applications. With a pragmatic approach to system design and a thorough understanding of observer functionality, we empower ourselves to build robust, elegant solutions that stand the test of time.

--

--