How to register event listeners in laravel 5.1

It’s quite open-ended as to where to register listeners for model events. One place is in the boot method within the EventServiceProvider class:

public function boot(DispatcherContract $events)

    // Do something

Be sure to import the namespace for the DispatcherContract at the top of the file:

use Illuminate\Contracts\Bus\Dispatcher as DispatcherContract;

Eloquent models provide a method for each event that you can pass an anonymous function to. This anonymous function receives an instance of the model that you can then act upon. So if you wanted to create a URL-friendly representation of an article headline each time your Article model was saved, you can do this by listening on the saving event:

  $article->slug = Str::slug($article->headline);

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Get The best In Web dev

Get The best In Web dev

Join dunebook and recieve best in Angular, React, Vue, Python, Java & more. Directly to your inbox once a week FREE !

You have Successfully Subscribed!

Pin It on Pinterest