Laravel Events, Listeners and Observers Complete Guide

Mohammed Muwanga
4 min readAug 10, 2024

Laravel Events, Listeners and Observers Complete Guide — Mohammed Muwanga

In Laravel, events and listeners are part of the event-driven architecture that allows developers to decouple different parts of the application. This pattern focuses on enabling different parts of your application to react to changes or actions which happen in other parts of the application.

  • Events: These are actions or occurrences happening in your application. For example, a user registers on the website, a new order is placed, or an ergonomic chair is added to the cart.
  • Listeners: These are classes that handle the events. When an event occurs, a listener can execute certain code in response to the event.

File and Directory Structure

  • Events: Created and stored in app/Events/.
  • Listeners: Created and stored in app/Listeners/.
  • Observers: Created and stored in app/Observers/.
  • Service Providers (EventServiceProvider and AppServiceProvider): Used to register events, listeners, and observers.
    app/Providers/EventServiceProvider and app/Providers/AppServiceProvider
  • Controllers: Used to handle HTTP requests and trigger events.

This organization ensures that your code is clean, maintainable, and follows Laravel’s conventions.

2. How Events and Listeners Work

  • Event Triggering: An event is typically triggered when a specific action occurs in the application. For example, you might trigger an event called UserRegistered when a user completes the registration process.
  • Event Listening: Once an event is triggered, Laravel checks for any listeners associated with that event. These listeners are then executed to perform actions in response to the event. For example, after a user registers, a listener might be responsible for sending a welcome email.

3. Example: User Registration

Let’s consider a scenario where we want to send a welcome email to a user after they register on a website.

1: Creating an Event, in terminal. This command generates an UserRegistered event class.

php artisan make:event UserRegistered

The UserRegistered event class looks something like. This event carries the user data as a payload.

class UserRegistered
{
public $user;

public function __construct(User $user)
{
$this->user = $user;
}
}

Step 2: Creating a Listener

php artisan make:listener SendWelcomeEmail --event=UserRegistered

This command creates a SendWelcomeEmail listener class that listens for the UserRegistered event. The class might look like:

class SendWelcomeEmail
{
public function handle(UserRegistered $event)
{
Mail::to($event->user->email)->send(new WelcomeEmail($event->user));
}
}

The listener’s handle method will be executed whenever the UserRegistered event is fired.

Step 3: Registering the Event and Listener

In the EventServiceProvider, you would map the event to the listener:

protected $listen = [
UserRegistered::class => [
SendWelcomeEmail::class,
],
];

Step 4: Firing the Event

When a user registers, you would fire the event like this. This can be anywhere in your application where you want to trigger the event, often in controller methods or service classes. Otherwise, you can use the service class, or even a model method depending on your application’s architecture.

event(new UserRegistered($user));

Laravel will automatically find and execute the listener(s) associated with this event.

Using Controller Files

Inside the controllers, its where you can handle HTTP requests and business logic. You may trigger events here.

Remember, the event, listener, and observer logic itself is not placed in the controller files.

For instance; If you have a UserController with a register method, you might trigger the UserRegistered event after the user is saved to the database:

use App\Events\UserRegistered;
use App\Models\User;

public function register(Request $request)
{
// Validate and create user
$user = User::create($request->all());

// Fire the event
event(new UserRegistered($user));

// Return response
return response()->json(['message' => 'User registered successfully']);
}

Observers in Laravel

Observers are used to group event listeners for a model. In fact, this implements the Pub/Sub design pattern. Laravel’s model observers allow you to listen to various model events such as creating, updating, deleting, etc., and execute code in response to these events.

How Observers Work

Observers provide a way to react to model lifecycle events without having to manually fire events. Laravel will automatically call the corresponding observer methods when a model event occurs.

Example: User Model Observer

Let’s consider a scenario where you want to perform certain actions when a User model is created, updated, or deleted. Even if its a product, like an office furniture piece such as an office chair, desk or anything so long as its a model in your system.

Step 1: Creating an Observer

This command generates a UserObserver class with methods corresponding to model events.

php artisan make:observer UserObserver --model=User

Step 2: Defining Observer Methods

In the UserObserver class, you can define methods that should be executed for specific model events:

class UserObserver
{
public function creating(User $user)
{
// Code to execute before a user is created
}

public function created(User $user)
{
// Code to execute after a user is created
}

public function updating(User $user)
{
// Code to execute before a user is updated
}

public function updated(User $user)
{
// Code to execute after a user is updated
}

public function deleting(User $user)
{
// Code to execute before a user is deleted
}

public function deleted(User $user)
{
// Code to execute after a user is deleted
}
}

Step 3: Registering the Observer

You need to register the observer in the boot method of your AppServiceProvider — located in app/Providers/AppServiceProvider.php.

use App\Models\User;
use App\Observers\UserObserver;

public function boot()
{
User::observe(UserObserver::class);
}

Differences and Relations Between Event Listeners and Observers

  • Scope: Event listeners can be used across the entire application and can listen for any event, not just those related to a model. Observers, on the other hand, are specifically tied to model lifecycle events.
  • Use Cases: Use event listeners when you need to handle application-wide events, and use observers when you need to respond to changes in a specific model’s lifecycle.
  • Operation: While both listen for events, listeners are more general-purpose, whereas observers are tailored for model events.

Finally

In Laravel, events, listeners, and observers are powerful tools specialized for building a responsive and decoupled application. They’ll help you manage how different parts of your application react to changes and events which make your code base easier to maintain and extend.

Sign up to discover human stories that deepen your understanding of the world.

Mohammed Muwanga
Mohammed Muwanga

Written by Mohammed Muwanga

Web Design, Development, SEO and Ergonomics

No responses yet

Write a response