Tuesday, September 8, 2020

Laravel Model Events observer

 Laravel’s Eloquent ORM is the rock-solid implementation of Active Record. Apart from other awesome features offered by Laravel Eloquent, Laravel implements Observer Pattern to fire some events, which can be listened to hook into, when various actions are performed on a model.

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. Source : Wikipedia

In this post, we will be learning about Laravel’s model events and how we can create model observers for grouping event listeners.

Laravel Model Events

If you have used Laravel for a medium to large scale project, you might have encountered a situation where you want to perform some action while your Eloquent model is processing. Laravel’s Eloquent provide a convenient way to add your own action while the model is completing or has completed some action.

For example, if you have Post model and you want to set post slug automatically when a post is created. You can listen to the saving event and set the post slug like below:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';

    protected $fillable = ['title', 'slug', 'content'];

    protected static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            $model->slug = str_slug($model->title);
        });
    }
}

Eloquent provides a handful of events to monitor the model state which are:

  • retrieved : after a record has been retrieved.
  • creating : before a record has been created.
  • created : after a record has been created.
  • updating : before a record is updated.
  • updated : after a record has been updated.
  • saving : before a record is saved (either created or updated).
  • saved : after a record has been saved (either created or updated).
  • deleting : before a record is deleted or soft-deleted.
  • deleted : after a record has been deleted or soft-deleted.
  • restoring : before a soft-deleted record is going to be restored.
  • restored : after a soft-deleted record has been restored.