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)
{
  parent::boot($events);

  User::creating(function($user)
  {
    // 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::saving(function($article)
{
  $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.

Pin It on Pinterest

Shares