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); });
Comments