How to implement event listeners in laravel?

Member

by jasen , in category: PHP Frameworks , 7 days ago

How to implement event listeners in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 7 days ago

@jasen 

In Laravel, event listeners can be implemented using the built-in Event system. Here's how you can implement event listeners in Laravel:


Step 1: Define an Event Class Create an Event class that extends the IlluminateFoundationEventsEvent class. This class should contain any data that you want to pass to the event listener.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php

namespace AppEvents;

use IlluminateFoundationEventsEvent;

class MyEvent extends Event
{
    public $data;

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


Step 2: Define an Event Listener Create an event listener class that implements the IlluminateContractsListener interface. This class should contain a handle() method that will be called when the event is fired.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php

namespace AppListeners;

use AppEventsMyEvent;

class MyEventListener
{
    public function handle(MyEvent $event)
    {
        // Handle the event
        $data = $event->data;

        // Add your logic here
    }
}


Step 3: Register the Event Listener Register the event listener in the EventServiceProvider class by adding it to the $listen array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php

namespace AppProviders;

use IlluminateFoundationSupportProvidersEventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        'AppEventsMyEvent' => [
            'AppListenersMyEventListener',
        ],
    ];

    public function boot()
    {
        parent::boot();
    }
}


Step 4: Fire the Event You can fire the event in your code using the event() helper function, passing an instance of the event class.

1
2
3
use AppEventsMyEvent;

event(new MyEvent($data));


When the event is fired, the handle() method of the event listener will be called and you can add your logic inside this method.


That's it! You have now implemented event listeners in Laravel.