0
0
LaravelHow-ToBeginner · 4 min read

How to Create Event in Laravel: Simple Guide with Example

In Laravel, create an event by running php artisan make:event EventName to generate the event class. Then, define the event properties and dispatch it using event(new EventName()) where needed.
📐

Syntax

To create an event in Laravel, use the artisan command to generate the event class. Then, dispatch the event in your code.

  • php artisan make:event EventName: Creates the event class.
  • event(new EventName()): Dispatches the event.

The event class can hold data you want to pass to listeners.

bash
php artisan make:event UserRegistered

// Dispatching the event in code
event(new UserRegistered($user));
💻

Example

This example shows how to create a UserRegistered event that carries a user object and how to dispatch it.

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;
    }
}

// In a controller or service where user registers:

$user = (object) ['name' => 'Alice', 'email' => 'alice@example.com'];
event(new UserRegistered($user));
Output
No visible output; event dispatched for listeners to handle.
⚠️

Common Pitfalls

Common mistakes when creating events in Laravel include:

  • Not running php artisan make:event and manually creating classes incorrectly.
  • Forgetting to import the event class before dispatching it.
  • Not passing required data to the event constructor.
  • Dispatching the event without listeners, which means no action happens.

Always ensure your event class uses Dispatchable and SerializesModels traits for best practice.

php
<?php
// Wrong: Missing import and traits
class UserRegistered {
    public $user;
    public function __construct($user) {
        $this->user = $user;
    }
}

// Right:
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserRegistered {
    use Dispatchable, SerializesModels;
    public $user;
    public function __construct($user) {
        $this->user = $user;
    }
}
📊

Quick Reference

Summary tips for creating events in Laravel:

  • Use php artisan make:event EventName to generate event classes.
  • Include Dispatchable and SerializesModels traits in event classes.
  • Pass any data needed by listeners through the event constructor.
  • Dispatch events with event(new EventName($data)).
  • Register listeners to respond to events for full functionality.

Key Takeaways

Create events using the artisan command for correct structure.
Include Dispatchable and SerializesModels traits in event classes.
Pass necessary data through the event constructor.
Dispatch events with the event() helper function.
Listeners must be registered to handle events effectively.