0
0
Laravelframework~5 mins

Defining events in Laravel

Choose your learning style9 modes available
Introduction

Events let your app react to things happening, like a user logging in. They help keep your code organized and easy to manage.

When you want to run some code after a user registers, like sending a welcome email.
When you need to update other parts of your app after a change, like logging activity.
When you want to separate different tasks that happen after an action, making your code cleaner.
When you want to trigger notifications after a specific event happens.
When you want to handle complex workflows by breaking them into smaller steps.
Syntax
Laravel
php artisan make:event EventName

// Event class example
namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class EventName
{
    use Dispatchable, SerializesModels;

    public $data;

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

Use php artisan make:event EventName to create a new event class.

Events usually carry data that listeners can use.

Examples
This command creates an event called UserRegistered.
Laravel
php artisan make:event UserRegistered
This event holds a $user object to share with listeners.
Laravel
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;
    }
}
Sample Program

This example defines an OrderPlaced event that carries an order ID. When an order is placed, the event is fired with the order ID.

Laravel
<?php

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderPlaced
{
    use Dispatchable, SerializesModels;

    public $orderId;

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

// Usage example in a controller or service

use App\Events\OrderPlaced;

function placeOrder(int $orderId) {
    // Order placing logic here

    event(new OrderPlaced($orderId));

    return "Order placed with ID: $orderId";
}

// Calling the function
echo placeOrder(123);
OutputSuccess
Important Notes

Events help keep your code clean by separating actions from reactions.

Always pass only the data listeners need to the event.

Use Laravel's event() helper to fire events easily.

Summary

Events are special classes that represent something happening in your app.

You create events with artisan and add data to share.

Fire events to let other parts of your app respond.