Listen to dispatched Laravel Eloquent Model as an Event

Panjeh
1 min readFeb 17, 2021

--

Before you start this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

This is a hidden feature of Laravel! In fact, in Laravel you can use any object made from any class as an event and pass it as an argument to the dispatch() method on theEvent facade.

In the following, we are listening to an event which is a user object.

Listen:


Event::listen
(User::class, function($payload)){
dd($payload)});

What we passed to the listen() method as the first argument isUser::class that is a string includes the User classname with its namespace, I mean 'App\Model\User'

What you get by dd is a user object.

We can dispatch like:

$event = User::find(1);Event::dispatch($event)

Usage:

Sometime you need to make an object with some “ready” properties and later complete it ( add more properties later or update its properties in another class). In such scenario you can pass the object among classes.

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

No responses yet