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.
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.
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;
}
}
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);
}
}
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,
);
}
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']);
}
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'];
}
}
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);
});
You might also like: