Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

Getting Started with Laravel Model Events

Published on by

Getting Started with Laravel Model Events image

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:

/**
* 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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
API Platform for Laravel image

API Platform for Laravel

Read article
Pan - A simple, lightweight, and privacy-focused product analytics php package image

Pan - A simple, lightweight, and privacy-focused product analytics php package

Read article
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article