Getting Started with Laravel Model Events


March 15th, 2018


Laravel Model events allow you to tap into various points in a model’s lifecycle, and can even prevent a save or delete from happening. The Laravel model events documentation outlines how you can hook into these events with event classes, but this article aims to build upon and fill in a few additional details on setting up events and listeners.

Events Overview

Eloquent has many events that you can hook into and add custom functionality to your models. The model has the following events at the time of writing:

  • retrieved
  • creating
  • created
  • updating
  • updated
  • saving
  • saved
  • deleting
  • deleted
  • restoring
  • restored

From the documentation here’s how they all work, and you can jump into the base Model class to see how these work as well:

The retrieved event will fire when an existing model is retrieved from the database. When a new model is saved for the first time, the creating and created events will fire. If a model already existed in the database and the save method is called, the updating / updated events will fire. However, in both cases, the saving / saved events will fire.

The documentation gives an excellent overview and explains how to hook into these events, but read further if you are new or unfamiliar with how to hook up event listeners to these custom model events.

Registering Events

The first thing you need to do in order to hook into an event on your model is to use the $dispatchesEvents property to register event objects, which will eventually get fired through the HasEvents::fireCustomModelEvent() method, which is called via the fireModelEvent() method. The fireCustomModelEvent() method looks like this at the time of writing:

2 * Fire a custom model event for the given event.
3 *
4 * @param string $event
5 * @param string $method
6 * @return mixed|null
7 */
8protected function fireCustomModelEvent($event, $method)
10 if (! isset($this->dispatchesEvents[$event])) {
11 return;
12 }
14 $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this));
16 if (! is_null($result)) {
17 return $result;
18 }

Some events, such as delete, will check to see if the event returns false and then back out of the operation. For example, you could use this hook to make some checks and prevent a user from being created or deleted.

Using the App\User model as an example, this is how you can configure your model event:

1protected $dispatchesEvents = [
2 'saving' => \App\Events\UserSaving::class,

You can use the artisan make:event command to create this event for you, but essentially this is what you’ll end up with:

3namespace App\Events;
5use App\User;
6use Illuminate\Queue\SerializesModels;
8class UserSaving
10 use SerializesModels;
12 public $user;
14 /**
15 * Create a new event instance.
16 *
17 * @param \App\User $user
18 */
19 public function __construct(User $user)
20 {
21 $this->user = $user;
22 }

Our event class provides a public $user property so you can access the User model instance during the saving event.

The next step to get this working is setting up an actual listener for the event. When the User model fires the saving event, listeners are called, thus allowing us to tap into the model during the event.

Creating an Event Listener

Now that our custom User model event fires during saving, we need to register a listener for it. We will look at using a model observer in a second, but I wanted to walk you through configuring an event and lister for a single event.

The event listener is like any other Laravel event listener, and the handle() method will accept an instance of the App\Events\UserSaving event class.

You can create this yourself by hand or use the php artisan make:listener command. However you create it, here’s what the listener class will look like:

3namespace App\Listeners;
5use App\Events\UserSaving as UserSavingEvent;
7class UserSaving
9 /**
10 * Handle the event.
11 *
12 * @param \App\Events\UserSavingEvent $event
13 * @return mixed
14 */
15 public function handle(UserSavingEvent $event)
16 {
17 app('log')->info($event->user);
18 }

I just added a call to the logger so I can inspect the model passed to the listener for now. For this to work, we need to register the listener in the EventServiceProvider::$listen property:

3namespace App\Providers;
5use Illuminate\Support\Facades\Event;
6use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
8class EventServiceProvider extends ServiceProvider
10 /**
11 * The event listener mappings for the application.
12 *
13 * @var array
14 */
15 protected $listen = [
16 \App\Events\UserSaving::class => [
17 \App\Listeners\UserSaving::class,
18 ],
19 ];
21 // ...

Now when the model dispatches the event, our listener is registered and is now called during the saving event.

Trying out the Event Handler

We can give our event listener code a try with a quick tinker session:

1php artisan tinker
2>>> factory(\App\User::class)->create();
3=> App\User {#794
4 name: "Aiden Cremin",
5 email: "",
6 updated_at: "2018-03-15 03:57:18",
7 created_at: "2018-03-15 03:57:18",
8 id: 2,
9 }

If you’ve registered your event and listener properly, you should see a JSON representation of the model in the laravel.log file:

1[2018-03-15 03:57:18] local.INFO: {"name":"Aiden Cremin","email":""}

Note that at this point the model doesn’t have a created_at or updated_at property. If you call save() again on the model, the log will have a new record with timestamps because the saving event fires on both newly created records and existing records:

1>>> $u = factory(\App\User::class)->create();
2=> App\User {#741
3 name: "Eloisa Hirthe",
4 email: "",
5 updated_at: "2018-03-15 03:59:37",
6 created_at: "2018-03-15 03:59:37",
7 id: 3,
8 }
9>>> $u->save();
10=> true

Stopping a Save

Some model events allow you to prevent the action from proceeding. In our ridiculous example, let’s say we didn’t want to allow a model save of any user with the name Paul contained in the $user->name property:

2 * Handle the event.
3 *
4 * @param \App\Events\UserSaving $event
5 * @return mixed
6 */
7public function handle(UserSaving $event)
9 if (stripos($event->user->name, 'paul') !== false) {
10 return false;
11 }

Within the based Eloquent Model::save() method, is this event check that will stop the save from happening based on the results of this event handler:

1public function save(array $options = [])
3 $query = $this->newQueryWithoutScopes();
5 // If the "saving" event returns false we'll bail out of the save and return
6 // false, indicating that the save failed. This provides a chance for any
7 // listeners to cancel save operations if validations fail or whatever.
8 if ($this->fireModelEvent('saving') === false) {
9 return false;
10 }

The save() method is a good example of how your custom events can tap into the model’s lifecycle and either passively do things like log data or dispatch a job.

Using Observers

If you are listening to multiple events, you may find it more convenient to use an observer class to group multiple events in one class. Here’s an example from the Eloquent events documentation:

3namespace App\Observers;
5use App\User;
7class UserObserver
9 /**
10 * Listen to the User created event.
11 *
12 * @param \App\User $user
13 * @return void
14 */
15 public function created(User $user)
16 {
17 //
18 }
20 /**
21 * Listen to the User deleting event.
22 *
23 * @param \App\User $user
24 * @return void
25 */
26 public function deleting(User $user)
27 {
28 //
29 }

You register observers through a service provider in the boot() method. A good place to add these is the the AppServiceProvider class:

2 * Bootstrap any application services.
3 *
4 * @return void
5 */
6public function boot()
8 User::observe(UserObserver::class);

Learn More

I recommend you read over the excellent Laravel events documentation to learn more about how events and listeners work across the framework. The Eloquent events documentation is a good reference for the available events and how to use observers. Last, I suggest finding usages of the fireModelEvent() method call by browsing through the Illuminate\Database\Eloquent\Model class to see how the events work with a model and the HasEvents trait which brings these events together.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.