How to Dispatch Event in Laravel: Simple Guide
In Laravel, you dispatch an event by calling
event(new EventClass()) or using Event::dispatch(new EventClass()). This triggers all listeners attached to that event class.Syntax
To dispatch an event in Laravel, you use either the event() helper function or the Event::dispatch() method. Both require you to pass an instance of your event class.
event(new EventClass()): Calls the global helper to dispatch the event.Event::dispatch(new EventClass()): Uses the Event facade to dispatch the event.
Your event class should be a simple PHP class that implements the ShouldBroadcast interface if broadcasting is needed, or just a plain class for internal events.
php
event(new UserRegistered($user)); // or use Illuminate\Support\Facades\Event; Event::dispatch(new UserRegistered($user));
Example
This example shows how to create a simple event and dispatch it when a user registers. The event carries the user data and can be listened to elsewhere in your app.
php
<?php namespace App\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class UserRegistered { use Dispatchable, SerializesModels; public $user; public function __construct($user) { $this->user = $user; } } // Dispatching the event somewhere in your code: $user = (object) ['name' => 'Alice']; event(new UserRegistered($user));
Output
No visible output; event dispatched and listeners (if any) will react accordingly.
Common Pitfalls
Common mistakes when dispatching events in Laravel include:
- Not importing the event class correctly, causing class not found errors.
- Forgetting to create or register event listeners, so nothing happens when the event is dispatched.
- Trying to dispatch an event without instantiating it (missing
newkeyword). - Using the event class name as a string instead of an object instance.
Always ensure your event class is imported and instantiated properly.
php
<?php // Wrong way (missing 'new') event(UserRegistered($user)); // Right way use App\Events\UserRegistered; event(new UserRegistered($user));
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Dispatch event | event(new EventClass()) | Dispatches the event using the helper function. |
| Dispatch event | Event::dispatch(new EventClass()) | Dispatches the event using the Event facade. |
| Create event class | php artisan make:event EventClass | Generates a new event class. |
| Listen to event | php artisan make:listener ListenerClass --event=EventClass | Creates a listener for the event. |
Key Takeaways
Use
event(new EventClass()) or Event::dispatch(new EventClass()) to dispatch events.Always instantiate your event class with
new before dispatching.Create and register listeners to respond to dispatched events.
Import event classes properly to avoid errors.
Use artisan commands to generate event and listener classes quickly.