This post refers to Laravel BootCamp tutorial.
[1] Define an event-related task
For example, a notification task.
Create a notification task via php artisan command:
php artisan make:notification NewChirp
Define the toMail method:
(app\notifications\newchirp.php)
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject("New Chirp from {$this->chirp->user->name}")
->greeting("New Chirp from {$this->chirp->user->name}")
->line(Str::limit($this->chirp->message, 50))
->action('Go to Chirper', url('/'))
->line('Thank you for using our application!');
}
[2] Create an Event
Create an event task via php artisan command:
php artisan make:event ChirpCreated
Update the ChirpCreated event to accept the newly created Chirp ($chirp) so that it can be passed to the notification task (NewChirp):
(app/Events/ChirpCreated.php)
public function __construct(public Chirp $chirp)
{
//
}
[3] Dispatch Event
Events can be dispatched anywhere in the application lifecycle.
In this example, the event will be dispatched from the Chirp Model.
Notice that the statement contains an array which means that there could be more than one event that can be dispatched altogether.
(app/Models/Chirp.php)
protected $dispatchesEvents = [
'created' => ChirpCreated::class,
];
[4] Create Event Listener
Create an event task via php artisan command:
php artisan make:listener SendChirpCreatedNotifications --event=ChirpCreated
Update the listener to send notifications.
(app/Listeners/SendChirpCreatedNotifications.php)
public function handle(ChirpCreated $event): void
{
//
foreach (User::whereNot('id', $event->chirp->user_id)->cursor() as $user) {
$user->notify(new NewChirp($event->chirp));
}
}
[5] Register Event Listener
(App\Providers\EventServiceProvider.php)
protected $listen = [
ChirpCreated::class => [
SendChirpCreatedNotifications::class,
],
...
];
References:
https://laravel.com/docs/10.x/events