0
0
Laravelframework~5 mins

Event dispatching in Laravel

Choose your learning style9 modes available
Introduction

Event dispatching helps your app respond to actions by sending messages that other parts can listen to and react.

When you want to run extra code after a user registers without changing the registration code.
When you need to send notifications after an order is placed.
When you want to log activities in your app without mixing logging code everywhere.
When you want to keep your code organized by separating concerns.
When you want to trigger multiple actions from one event.
Syntax
Laravel
event(new EventName($data));
Use the event() helper to dispatch events easily.
Events are usually classes that hold data and describe what happened.
Examples
Dispatches a UserRegistered event with the user data.
Laravel
event(new UserRegistered($user));
Sends an OrderPlaced event to notify listeners.
Laravel
event(new OrderPlaced($order));
Sample Program

This example shows how to create a simple event UserRegistered with user data. Then it dispatches the event using event(). Finally, it simulates a listener reacting by printing a welcome message.

Laravel
<?php

namespace App\Events;

class UserRegistered
{
    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }
}

// In a controller or service
$user = (object) ['name' => 'Alice'];
event(new UserRegistered($user));

// Listener example (usually in separate class)
// Just for demonstration:
function onUserRegistered($event) {
    echo "Welcome, {$event->user->name}!\n";
}

// Simulate listener call
onUserRegistered(new UserRegistered($user));
OutputSuccess
Important Notes

Events help keep your code clean by separating what happens from how you react.

Listeners are classes or functions that handle events when they are dispatched.

Laravel can automatically discover and run listeners if you register them properly.

Summary

Event dispatching sends messages about actions in your app.

Use event(new EventName($data)) to dispatch events.

Listeners respond to events to perform tasks like notifications or logging.