Laravel - Event Handling

Laravel - Event Handling

Laravel - Event Handling

Laravel’s event handling system allows you to subscribe to and listen to events in your application, enabling decoupled and flexible architecture. Events are useful for sending notifications, logging activities, broadcasting, and more.

Step 1: Events and Listeners

Laravel’s event system consists of:

  • Events: Represent an action that has occurred in the application.
  • Listeners: Handle the event and execute logic when it is triggered.

For example, when a user registers, an event like UserRegistered is fired, and a listener SendWelcomeEmail sends an email.

Step 2: Creating Events and Listeners

Laravel provides an artisan command to generate events and listeners.

1. Generate an Event

Run the following command to create an event:

php artisan make:event UserRegistered

This creates a file in app/Events/UserRegistered.php:

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; } }

This event is triggered when a user registers.

2. Generate a Listener

Run the command:

php artisan make:listener SendWelcomeEmail --event=UserRegistered

This creates app/Listeners/SendWelcomeEmail.php:

namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Facades\Mail; class SendWelcomeEmail implements ShouldQueue { use InteractsWithQueue; public function __construct() { // } public function handle(UserRegistered $event) { // Send welcome email Mail::to($event->user->email)->send(new \App\Mail\WelcomeMail($event->user)); } }
  • ShouldQueue: Makes the listener execute asynchronously.
  • handle(): Defines the action when the event occurs.

Step 3: Register Events and Listeners

Laravel automatically discovers events and listeners, but you can manually register them in:

File: app/Providers/EventServiceProvider.php

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

Run the following command to cache the events and listeners:

php artisan event:cache

Step 4: Firing an Event

To trigger the event, use:

use App\Events\UserRegistered; use App\Models\User; $user = User::find(1); event(new UserRegistered($user));

Alternatively, you can use the dispatch() method:

UserRegistered::dispatch($user);

Step 5: Using Event Subscribers (Optional)

Subscribers handle multiple events in a single class.

1. Create a Subscriber

Run:

php artisan make:listener UserEventSubscriber

Modify app/Listeners/UserEventSubscriber.php:

namespace App\Listeners; use App\Events\UserRegistered; class UserEventSubscriber { public function handleUserRegistered($event) { // Send welcome email Mail::to($event->user->email)->send(new \App\Mail\WelcomeMail($event->user)); } public function subscribe($events) { $events->listen( UserRegistered::class, [UserEventSubscriber::class, 'handleUserRegistered'] ); } }

2. Register the Subscriber

In EventServiceProvider.php:

protected $subscribe = [ \App\Listeners\UserEventSubscriber::class, ];

Step 6: Testing the Event System

Use the artisan command to test:

php artisan tinker

Then dispatch the event:

$user = App\Models\User::first(); event(new App\Events\UserRegistered($user));

Check if the listener executes properly.

Conclusion

✅ Laravel’s event system helps decouple logic.
✅ Events can be queued for better performance.
✅ Auto-discovery simplifies event-listener management.
✅ Useful for sending notifications, logging, broadcasting, etc.

Would you like an example of real-time broadcasting using WebSockets? 🚀

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close