Complete the code to dispatch an event in Laravel.
<?php
use App\Events\UserRegistered;
function registerUser($user) {
// Dispatch the event
event(new [1]($user));
}In Laravel, events are dispatched by creating a new event instance and passing it to the event() helper. Here, UserRegistered is the event class.
Complete the code to listen for the UserRegistered event in Laravel.
<?php namespace App\Listeners; use App\Events\UserRegistered; class SendWelcomeEmail { public function handle([1] $event) { // Send email logic here } }
The listener's handle method receives the event object as a parameter. The type hint must match the event class, here UserRegistered.
Fix the error in the event listener registration in Laravel's EventServiceProvider.
protected $listen = [
[1]::class => [
SendWelcomeEmail::class,
],
];The $listen array maps event classes to their listeners. The key must be the event class, here UserRegistered::class.
Fill both blanks to create a listener that handles the event and logs a message.
<?php namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Support\Facades\Log; class LogUserRegistration { public function handle([1] $event) { Log::[2]('User registered: ' . $event->user->email); } }
Log::error instead of Log::info for normal logs.The handle method receives the event object typed as UserRegistered. The Log::info method logs an informational message.
Fill all three blanks to create an event-driven flow that dispatches an event, listens, and handles it.
<?php
// Dispatch event
function registerUser($user) {
event(new [1]($user));
}
// Listener handle method
class SendNotification
{
public function handle([2] $event)
{
// Notify user
notify($event->user);
}
}
// EventServiceProvider mapping
protected $listen = [
[3]::class => [
SendNotification::class,
],
];All blanks require the event class UserRegistered to correctly connect dispatching, listening, and mapping in Laravel's event-driven architecture.