Palzin Track
Get 15% off with code PTRACKSIGNUP15 

Laravel Diary Logo

Power of Laravel 10 Event Listener for Reactive Applications

laravel
Table of Contents

Harness the Power of Laravel 10 Event Listener for Reactive Applications

Event-driven architecture has become a cornerstone in modern web applications, providing a way to execute code in response to various actions or triggers. Laravel has long supported this pattern, and Laravel 10 continues to simplify and enhance the way developers can work with events and listeners. Let's explore the world of events and listeners in Laravel 10 and illuminate how you can utilize them in real-world scenarios.

In Laravel, events are signals dispatched to the system indicating that some condition or action has taken place. Listeners are the logic that respond to these signals. Together, they offer a convenient way of separating concerns and introducing side-effects without cluttering your main business logic.

Let's consider a common scenario in nearly all modern applications, user registration. When a user registers, several things need to happen:

  • Sending a welcome email
  • Logging the registration for analytics
  • Notifying the admin team

Without events, these operations might be stuffed into the user registration method, making it bloated and difficult to maintain.

With events, you simply raise a UserRegistered event and various listeners handle the rest.

First, we'll create an event using Laravel's Artisan command-line tool:

php artisan make:event UserRegistered

Here's a simplified event class for user registration:

namespace App\\Events;

use App\\Models\\User;
use Illuminate\\Foundation\\Events\\Dispatchable;
use Illuminate\\Queue\\SerializesModels;

class UserRegistered
{
    use Dispatchable, SerializesModels;

    public $user;

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

Next, we generate listeners for our UserRegistered event:

php artisan make:listener SendWelcomeEmail --event=UserRegistered
php artisan make:listener LogRegistration --event=UserRegistered

These will produce two classes: SendWelcomeEmail and LogRegistration within the app/Listeners directory.

// SendWelcomeEmail listener example
namespace App\\Listeners;

use App\\Events\\UserRegistered;
use App\\Mail\\WelcomeEmail;
use Illuminate\\Support\\Facades\\Mail;

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

In Laravel's EventServiceProvider, we map events to listeners:

protected $listen = [
    'App\\Events\\UserRegistered' => [
        'App\\Listeners\\SendWelcomeEmail',
        'App\\Listeners\\LogRegistration',
    ],
];

Laravel 10 introduces several new features that enhance event handling. For example:

  • Improved event broadcasting
  • Better listener conditions with new methods for filtering when a listener should run
  • Enhanced listener queuing options

Event broadcasting in Laravel allows you to broadcast your Laravel events over a WebSocket connection, making it simple to build real-time, interactive web applications. In Laravel 10, event broadcasting has been improved to work more seamlessly with client-side frameworks like Vue.js and React.

Example: Real-Time Notifications

Suppose you want to notify users in real-time when a new article is published in your application. You can broadcast the ArticlePublished event using Laravel Echo and Pusher or any other compatible broadcasting driver.

First, define the event and implement the ShouldBroadcast interface:

namespace App\\Events;

use App\\Models\\Article;
use Illuminate\\Broadcasting\\Channel;
use Illuminate\\Contracts\\Broadcasting\\ShouldBroadcast;
use Illuminate\\Queue\\SerializesModels;

class ArticlePublished implements ShouldBroadcast
{
    use SerializesModels;

    public $article;

    public function __construct(Article $article)
    {
        $this->article = $article;
    }
    
    public function broadcastOn()
    {
        return new Channel('articles');
    }
}

When this event is dispatched, it's also sent to the specified broadcast channel, and any client-side applications listening on that channel will receive the event in real-time.

// Using Laravel Echo to listen for the event on the client-side
Echo.channel('articles')
    .listen('ArticlePublished', (e) => {
        console.log('A new article has been published:', e.article);
    });

In previous versions, conditional listeners would require you to manually check a condition within the handle method. Laravel 10 introduces a cleaner way to specify conditions directly in the Event Service Provider.

Example: Conditional Listener on User Type

Let's say we want to send a special notification to admin users when a new ticket is raised but only if it's marked as urgent. We can now use the Illuminate\\Events\\ListenerCondition features.

In EventServiceProvider.php, you can do something like this:

use App\\Events\\TicketRaised;
use App\\Listeners\\SendAdminNotification;
use Illuminate\\Events\\ListenerCondition;

protected $listen = [
    TicketRaised::class => [
        [SendAdminNotification::class, ListenerCondition::if(fn ($event) => $event->ticket->is_urgent)],
    ],
];

Laravel 10 provides more granular control over listener queuing, allowing you to specify the connection, queue, and delay within the listener itself, without needing to define these properties in the event.

Example: Delayed Listener Execution for Non-Critical Notifications

Consider you have a listener that sends out a non-critical notification to users whenever their profile is updated. You don't need this to happen in real-time, so you can defer the execution to reduce the load on your immediate queue.

namespace App\\Listeners;

use App\\Events\\ProfileUpdated;
use Illuminate\\Contracts\\Queue\\ShouldQueue;

class SendProfileUpdateNotification implements ShouldQueue
{
    public $connection = 'sqs';
    public $queue = 'notifications';
    public $delay = 600; // Delay by 10 minutes
    
    public function handle(ProfileUpdated $event)
    {
        // send notification logic
    }
}

By providing $connection, $queue, and $delay properties, you can specify exactly how and when this listener should be queued, offering more precise control over the asynchronous handling of your background tasks.

These new features in Laravel 10 allow for more powerful, flexible, and maintainable event-driven systems that can scale with your application's complexity.

Ensure to explore the official documentation to stay updated with all the latest advancements.

Public variables within a listener are those made available to the handle method, commonly accessed via the event object.

As for return statements in listeners, they are not mandatory in Laravel unless you are using an event subscriber that might handle multiple events and could dictate a return value to stop the propagation of the event to other listeners. In most use cases, listeners are void functions—they simply perform an action without needing to return any data. However, if a listener returns false, it will prevent the propagation of the event to other listeners.

Laravel 10 continues to refine event-driven development, making it one of the framework's most powerful features. By embracing events and listeners, you can create applications that are easy to understand, maintain, and extend. As you've seen with the user registration example, events free your core application logic from secondary concerns and side-effects. So, take the leap with Laravel 10 and watch your applications respond and scale like never before.

::Share it on::

Comments (0)

What are your thoughts on "Power of Laravel 10 Event Listener for Reactive Applications"?

You need to create an account to comment on this post.