Tip For Laravel Events

in laravel if you want to create an event and a listener you usually have to go through the long road of Registering Events & Listeners and it produces even more headache if you decided to include them inside a package you are building.

but actually there is a much easier/shorter way of doing it, so for a start lets see the most basic way of firing an event and catching it.

1

  • anywhere in your app
event('some-event');
  • inside app/Providers/EventServiceProvider.php boot()
Event::listen('some-event', function () {
    // do something ...
});

- But what if you want to send some data through the wire, do we need to go back to the long version ?
- Not necessarily.

2

  • anywhere in your app
event('some-event', $data);
  • inside app/Providers/EventServiceProvider.php boot()
Event::listen('some-event', function ($data) { 
    // $data
});

//
// if $data was an array ex."['a'=>'some', 'b'=>'thing']"
// - you can either call it through the named keys
//
Event::listen('some-event', function ($a, $b) { 
    dd($a, $b)
});

//
// - or by using spread operator
//
Event::listen('some-event', function (...$data) { 
    list($a, $b, $etc) = $data;

    dd($a, $b, $etc)
});

- Okay good, but what about using queues ?
- No problem.

3

  • anywhere in your app
event('some-event', $data);
  • create a job with
php artisan make:job ProcessSomeEvent
  • inside app/Providers/EventServiceProvider.php boot()
Event::listen('some-event', function ($data) {
    ProcessSomeEvent::dispatch($data);
});
  • now inside app/Jobs/ProcessSomeEvent.php
// ...

protected $data;

public function __construct($data)
{
    $this->data = $data;
}
php artisan queue:work

However there is a gotcha.

if you are going to send a modal through the event, you will need to serialize & deserialize the sent data,
Which in that case you should fallback to Registering Events & Listeners.


# Extra Tip

you can also listen to the event from a model

protected static function boot()
{
    parent::boot();

    app('events')->listen('some-event', function ($data) {
        // $data
    });
}

or from a controller

public function __construct()
{
    app('events')->listen('some-event', function ($data) {
        // $data
    });
}

 

…btw you can listen to events anywhere you want, for example inside “database/seeds/DatabaseSeeder@run” so you can do something only when you run
php artisan db::seed.
but keep in mind that the event listener have to be running before the event gets fired.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.