Laravel, one of the most popular PHP frameworks, offers a wide range of functionalities to help developers build robust and scalable applications. Among its many features, Laravel Events stand out as an efficient way to monitor and react to various occurrences in your app. In this blog post, we’ll take an in-depth look at how to use and maximize Laravel Events.

What are Laravel Events?

Laravel Events provide an observer implementation, serving as a way to subscribe and listen for different events in your application. Think of it as a notification system where various parts of your app can notify others when a specific action occurs. For instance, you might want to send an email to a user when an order is shipped. Instead of coupling your order processing logic with the email sending logic, you can trigger an event and have a listener handle the email sending.

Registering Events and Listeners

In Laravel, the primary spot for registering events and their listeners is the EventServiceProvider. Here’s a basic example of registering an event:

protected $listen = [
    'OrderShipped' => [
        'SendShipmentNotification',
    ],
];

In this example, when the OrderShipped event is triggered, the SendShipmentNotification listener will handle the response.

Generating Events and Listeners

Laravel’s Artisan command-line tool makes it easy to generate events and listeners:

php artisan event:generate

Running this command will create any events or listeners that are listed in your EventServiceProvider.

Writing Event Listeners

Listeners are the actions you want to be executed when an event is triggered. For instance, when an ‘OrderShipped’ event is fired, you might want to send a notification:

public function handle(OrderShipped $event)
{
    // Send notification, process further, etc.
}

The handle method of the listener receives the event instance, allowing you to access any public properties or methods on the event.


Manual Listener Registration

If for some reason you’d prefer to register listeners manually (maybe you want more control or need conditional registration), Laravel has you covered:

Event::listen(OrderShipped::class, SendShipmentNotification::class);

This method allows you to pair events with listeners directly.


Wildcard Event Listeners

For scenarios where you want to listen to multiple events with a single listener, Laravel offers wildcard listeners:

Event::listen('event.*', function ($eventName, array $data) {
    // Handle all events that start with 'event.'
});

This can be particularly useful when you want to perform a general action for a group of related events.


Stoppable Events

Laravel introduces the concept of stoppable events, allowing you to halt the propagation of an event based on certain conditions:

if ($event->order->cancelled) {
    return false;
}

If a listener returns false, all subsequent listeners for that event will not run.


Event Discovery

One of the elegant features of Laravel is its ability for event discovery. Instead of manually registering events and listeners, Laravel can automatically discover them, making the process cleaner and more organized. To utilize this, ensure:

public function shouldDiscoverEvents()
{
    return true;
}

Customizing Event Discovery

To customize which directories Laravel should look into for event discovery, you can define them:

public function discoverEventsWithin()
{
    return [
        'app/Listeners',
        'app/Events',
    ];
}

This ensures Laravel only discovers events and listeners within the specified directories.

Example

Let’s create a step-by-step demonstration of Laravel’s event system using a common scenario: User Registration. When a user registers, we’ll fire an event to send a welcome email.

Step 1: Setup

Ensure you have a fresh Laravel installation ready. If not, you can create one using Composer:

composer create-project laravel/laravel laravel-events-demo

Step 2: Create the Event

Generate the UserRegistered event:

php artisan make:event UserRegistered

This will create a new file in the app/Events directory.

Edit app/Events/UserRegistered.php:

namespace App\Events; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; use App\Models\User; class UserRegistered { use Dispatchable, InteractsWithSockets, SerializesModels; public $user; public function __construct(User $user) { $this->user = $user; } }

Here, the event expects a User object upon its creation, which we’ll use to send the welcome email.

Step 3: Create the Listener

Generate the listener for the UserRegistered event:

php artisan make:listener SendWelcomeEmail --event=UserRegistered

This creates a SendWelcomeEmail listener in the app/Listeners directory.

Edit app/Listeners/SendWelcomeEmail.php:

namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class SendWelcomeEmail { public function handle(UserRegistered $event) { // Logic to send a welcome email to $event->user // For demo purposes, we'll just log the action. \Log::info('Welcome email sent to ' . $event->user->email); } }

Here, whenever the UserRegistered event is fired, the listener logs a message.

Step 4: Register the Event & Listener

Register the event and its listener in app/Providers/EventServiceProvider.php:

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

Step 5: Fire the Event

Now, let’s simulate a user registration and fire the event.

Assuming you have a route and controller for user registration, in the method where the user is registered, fire the event:

use App\Events\UserRegistered; // ... User registration logic ... // Fire the event event(new UserRegistered($user));

When you register a user, the UserRegistered event will be fired, and the SendWelcomeEmail listener will be executed, logging the message.

Conclusion

Laravel Events offer a powerful and efficient way to decouple various aspects of your application, promoting cleaner and more maintainable code. Whether you’re sending notifications, logging activities, or integrating third-party services, Laravel Events can be an indispensable tool in your development toolkit. As with all things Laravel, the key is to understand the underlying concepts and apply them effectively to your unique needs.

Categorized in: