Language:

Search

Events and Listeners in Laravel

  • Share this:
Events and Listeners in Laravel

In Laravel, events are used to trigger actions and listeners are used to listen for those actions and perform some logic in response.

Here's an overview of how events and listeners work in Laravel:

Also Read: Laravel Hosting Options

  1. An event is triggered using the event facade or the event helper function.
  2. Laravel's event dispatcher listens for the event and passes it to the registered listeners.
  3. The listeners perform the logic that you have defined in response to the event.

Here's an example of how you can create an event and a listener in Laravel:

// Define the event
class UserRegisteredEvent extends Event
{
    use SerializesModels;
    public $user;
    /**
     * Create a new event instance.
     *
     * @param  User  $user
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }
}
// Define the listener
class SendWelcomeEmailListener
{
    /**
     * Handle the event.
     *
     * @param  UserRegisteredEvent  $event
     * @return void
     */
    public function handle(UserRegisteredEvent $event)
    {
        Mail::to($event->user->email)->send(new WelcomeEmail($event->user));
    }
}

In this example, we create an event UserRegisteredEvent and a listener SendWelcomeEmailListener. When the event is triggered, the listener's handle method is executed, which sends a welcome email to the newly registered user.

You can register the event and the listener in the EventServiceProvider:

protected $listen = [
    UserRegisteredEvent::class => [
        SendWelcomeEmailListener::class,
    ],
];

Now, you can trigger the event wherever you want by using the event helper function:

event(new UserRegisteredEvent($user));

Once you have registered the event and listener, Laravel's event dispatcher will handle the rest, automatically triggering the listeners when the event is fired.

Related: Get $200 Credit with Digital Ocean

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques