The Laravel docs say I should put the model events in the EventServiceProvider boot() method like this.
public function boot(DispatcherContract $events)
{
Raisefund::saved(function ($project) {
//do something
});
}
But I have many models that I want to listen to.
So I was wondering if it is the right way to put it all in the EventServiceProvider.
Yes that's correct, the EventServiceProvider is the best place for it.
However you can create Observers to keep it clean. I will give you a quick example.
EventServiceProvider
<?php
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\Models\Users;
use App\Observers\UserObserver;
/**
* Event service provider class
*/
class EventServiceProvider extends ServiceProvider
{
/**
* Boot function
*
* @param DispatcherContract $events
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
Users::observe(new UserObserver());
}
}
UserObserver
<?php
namespace App\Observers;
/**
* Observes the Users model
*/
class UserObserver
{
/**
* Function will be triggerd when a user is updated
*
* @param Users $model
*/
public function updated($model)
{
}
}
The Observer will be the place where the saved, updated, created, etc.. functions will be executed.
More information about Observers: http://laravel.com/docs/5.0/eloquent#model-observers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With