onsa
12/19/2016 - 12:07 PM

Register an observer for a model (https://laravel.com/docs/master/eloquent#observers).

Register an observer for a model (https://laravel.com/docs/master/eloquent#observers).

<?php

//  Service providers can listen to individual events or register whole observers.
namespace App\Providers;

use App\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public static function boot()
      {
        parent::boot();

//  Listen to individual events
//	Events such as creating, updating, saving and deleting can be cancelled by returning false in the corresponding method.
        User::creating(function($user)
          {
            if ( ! $user->isValid()) return false;
          });

//	Events such as created, updated, saved and deleted can fire other events.
        User::deleted(function($user)
          {
            //	send email to admin
          });
        }

//  OR register whole observers
        User::observe(UserObserver::class);
    }
}
<?php

namespace App\Observers;

use App\User;

class UserObserver
{
    /**
     * Listen to the User created event.
     *
     * @param  User  $user
     * @return void
     */
    public function created(User $user)
    {
        //
    }

    /**
     * Listen to the User deleting event.
     *
     * @param  User  $user
     * @return void
     */
    public function deleting(User $user)
    {
        //
    }
}