Where shoud i put save event listener model in laravel 5.1

Laravel docs say that I should put model events in an 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 this is the right thing to do in the EventServiceProvider .

+7
php eloquent laravel
source share
2 answers

Yes, that's right, EventServiceProvider is the best place for it.

However, you can create Observers to be 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) { } } 

Observer will be the place where the saved , updated , created , etc. functions will be executed.

Additional Observer Information: http://laravel.com/docs/5.0/eloquent#model-observers

+10
source share

You can register listener callbacks in your boot models, for example:

 class User extends Eloquent { protected static function boot() { parent::boot(); static::deleting(function($user) { //deleting listener logic }); } 
+7
source share

All Articles