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);
});
Deven Rathore

Deven is an Entrepreneur, and Full-stack developer, Constantly learning and experiencing new things. He currently runs CodeSource.io and Dunebook.com.

Published by
Deven Rathore

Recent Posts

3 Ways to Get the Most Out of Your University’s Virtual Computer Lab

IT is more important than ever in the world of higher education, and yet with…

20 hours ago

Top Tips for Learning Java Programming

If you’re here for the top tips, we assume you’re ahead of the “how to…

1 day ago

Neural Networks for Creating Blog Texts

The world is progressing at unprecedented rates at the current moment, especially in terms of…

2 days ago

Top 20 Opensource Python Tkinter Projects

This article will highlight the Top 20 Opensource Python Tkinter Projects which we believe will…

4 days ago

Beginners guide to Sneaker Proxies

With their numerous applications in streamlining the data flow, securing both the servers and the…

1 week ago

Top 20 Node.js dashboard templates

In this article, We will be looking at some of the top Node.js dashboard templates.…

1 week ago