Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put model saving event listener in laravel 5.1

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.

like image 228
refear99 Avatar asked Jul 09 '15 09:07

refear99


Video Answer


1 Answers

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

like image 154
Szenis Avatar answered Sep 28 '22 00:09

Szenis