Getting Started with Laravel Model Events
Published on by Paul Redmond
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, thecreating
andcreated
events will fire. If a model already existed in the database and thesave
method is called, theupdating
/updated
events will fire. However, in both cases, thesaving
/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:
/** * Fire a custom model event for the given event. * * @param string $event * @param string $method * @return mixed|null */protected function fireCustomModelEvent($event, $method){ if (! isset($this->dispatchesEvents[$event])) { return; } $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this)); if (! is_null($result)) { return $result; }}
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:
protected $dispatchesEvents = [ '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:
<?php namespace App\Events; use App\User;use Illuminate\Queue\SerializesModels; class UserSaving{ use SerializesModels; public $user; /** * Create a new event instance. * * @param \App\User $user */ public function __construct(User $user) { $this->user = $user; }}
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:
<?php namespace App\Listeners; use App\Events\UserSaving as UserSavingEvent; class UserSaving{ /** * Handle the event. * * @param \App\Events\UserSavingEvent $event * @return mixed */ public function handle(UserSavingEvent $event) { app('log')->info($event->user); }}
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:
<?php namespace App\Providers; use Illuminate\Support\Facades\Event;use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider{ /** * The event listener mappings for the application. * * @var array */ protected $listen = [ \App\Events\UserSaving::class => [ \App\Listeners\UserSaving::class, ], ]; // ...}
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:
php artisan tinker>>> factory(\App\User::class)->create();=> App\User {#794 name: "Aiden Cremin", email: "josie05@example.com", updated_at: "2018-03-15 03:57:18", created_at: "2018-03-15 03:57:18", id: 2, }
If you’ve registered your event and listener properly, you should see a JSON representation of the model in the laravel.log
file:
[2018-03-15 03:57:18] local.INFO: {"name":"Aiden Cremin","email":"josie05@example.com"}
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:
>>> $u = factory(\App\User::class)->create();=> App\User {#741 name: "Eloisa Hirthe", email: "gottlieb.itzel@example.com", updated_at: "2018-03-15 03:59:37", created_at: "2018-03-15 03:59:37", id: 3, }>>> $u->save();=> 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:
/** * Handle the event. * * @param \App\Events\UserSaving $event * @return mixed */public function handle(UserSaving $event){ if (stripos($event->user->name, 'paul') !== false) { return false; }}
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:
public function save(array $options = []){ $query = $this->newQueryWithoutScopes(); // If the "saving" event returns false we'll bail out of the save and return // false, indicating that the save failed. This provides a chance for any // listeners to cancel save operations if validations fail or whatever. if ($this->fireModelEvent('saving') === false) { return false; }
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:
<?php namespace App\Observers; use App\User; class UserObserver{ /** * Listen to the User created event. * * @param \App\User $user * @return void */ public function created(User $user) { // } /** * Listen to the User deleting event. * * @param \App\User $user * @return void */ public function deleting(User $user) { // }}
You register observers through a service provider in the boot()
method. A good place to add these is the the AppServiceProvider
class:
/** * Bootstrap any application services. * * @return void */public function boot(){ 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.