How to Bind to Eloquent Model Event in Laravel 5

Whenever a Laravel model is modified there are a number of events that fire that allow you to trigger your own action(s). For example, in my PoliticsEQ application I needed to calculate some statistics about keywords and sentiment scores and store them in a separate table to improve performance for some of the front in graphs. The challenge was making sure the keyword statistics table was updated whenever a keyword was added or updated.

Laravel gives you the following events right out of the box: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. You can get the particulars here. Most of them are pretty intuitive.

In my case it made sense to use the “saved” event. To make this happen was remarkably. All I had to do was create a new “Service Provider” and use the Event::saved pattern in the provider’s boot method.

So first I created a KeywordStats provider.


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Keyword, App\KeywordStat;
use Log;

class KeywordStats extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        Keyword::saved(function($keyword) {
          $stat = KeywordStat::where('keyword_name', $keyword->name)->first();
          if (!$stat) {
            $stat = new KeywordStat(['keyword_name'=>$keyword->name]);
          }
          $stat->sentiment_avg = Keyword::where('name', $keyword->name)->avg('sentiment_score');
          $stat->total_usages = Keyword::where('name',$keyword->name)->get()->count();
          $stat->save();
          Log::info("Updated {$keyword->name} / avg: {$stat->sentiment_avg} / count: {$stat->total_usages}");
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        
    }
}

Then I simply registered the provider in the config/app.php providers array:


    App\Providers\KeywordStats::class,