Event-Driven Architecture in Laravel 11: Going Beyond the Basics

Hello laravel web developers!, In this article, we'll see how to create event-driven architecture in laravel 11. Event-driven architecture (EDA) in Laravel allows different parts of your application to communicate asynchronously using events and listeners. This design pattern helps decouple complex workflows, ensuring each component can respond to changes in state or user actions without directly depending on others.

In Laravel, events represent actions or triggers, while listeners handle the response logic. Broadcasting allows events to be transmitted in real-time to clients via WebSockets.

Real-World Scenario: User Registration with Email Notification

Imagine an application where, after user registration, we need to send an email, log the event, and trigger a welcome notification. With event-driven architecture, this workflow becomes modular and easy to extend.

Event-Driven Architecture in Laravel 11: Going Beyond the Basics

 

Step-by-Step Guide to Implement Event-Driven Architecture in Laravel 11

Step 1: Create the Event

An event in Laravel is a class that represents an action. Let's create a UserRegistered event.

php artisan make:event UserRegistered

In the UserRegistered event class, we pass the User object.

app/Events/UserRegistered.php

namespace App\Events;

use App\Models\User;
use Illuminate\Queue\SerializesModels;

class UserRegistered
{
    use SerializesModels;

    public $user;

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

 

Step 2: Create the Listeners

Next, we create listeners that handle the actions in response to the UserRegistered event.

php artisan make:listener SendWelcomeEmail
php artisan make:listener LogRegistration

Now, implement the listeners:

app/Listeners/SendWelcomeEmail.php

namespace App\Listeners;

use App\Events\UserRegistered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mail;

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

app/Listeners/LogRegistration.php 

namespace App\Listeners;

use App\Events\UserRegistered;
use Log;

class LogRegistration
{
    public function handle(UserRegistered $event)
    {
        Log::info('User registered: ' . $event->user->email);
    }
}

 

Step 3: Register Events and Listeners

By default, Laravel will automatically find and register your event listeners by scanning your application's Listeners directory. When Laravel finds any listener class method that begins with handle or __invoke, Laravel will register those methods as event listeners for the type-hinted event in the method's signature.

Next, register your event and listeners using the withEvents method in your application's bootstrap/app.php file.

bootstrap/app.php file

->withEvents(discover: [
    __DIR__.'/../app/Events/UserRegistered',
    __DIR__.'/../app/Listeners/SendWelcomeEmail',
    __DIR__.'/../app/Listeners/LogRegistration',
])

Manually Registering Events

Using the Event facade, you may manually register events and their corresponding listeners within the boot method of your application's AppServiceProvider.

use App\Events\UserRegistered;
use App\Listeners\SendWelcomeEmail;
use App\Listeners\LogRegistration;
use Illuminate\Support\Facades\Event;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Event::listen(
        UserRegistered::class,
        SendWelcomeEmail::class,
        LogRegistration::class,
    );
}

 

Step 4: Trigger the Event

Now, let's trigger the UserRegistered event upon successful user registration.

app/Http/Controllers/Auth/RegisterController.php

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

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

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

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

 

Step 5: Broadcasting the Event

To broadcast the event in real-time to clients (e.g., using WebSockets), modify the event to implement the ShouldBroadcast interface.

app/Events/UserRegistered.php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class UserRegistered implements ShouldBroadcast
{
    use InteractsWithSockets;

    public $user;

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

    public function broadcastOn()
    {
        return ['user-registered'];
    }
}

 

Step 6: Listening for Broadcasted Events on the Client Side

Using Laravel Echo and Pusher, you can listen to broadcasted events on your JavaScript front end.

Echo.channel('user-registered')
    .listen('UserRegistered', (e) => {
        console.log('User registered:', e.user);
    });

 

Testing the Event-Driven Workflow
  • Register a user.
  • Verify that a welcome email is sent.
  • Check the log file to confirm the registration was logged.
  • Optionally, see the event broadcasted in real-time if configured

 

Benefits of Event-Driven Architecture
  • Decoupling: Events and listeners are separated from the core logic, making the codebase cleaner and easier to manage.
  • Asynchronous Processing: Listeners can be queued, allowing for asynchronous handling of time-consuming tasks like sending emails.
  • Scalability: New listeners can be added without changing the original logic, making it easier to extend functionality.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS