Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Working with Laravel Model Events

Published on by

Working with Laravel Model Events image

When working with Eloquent Models, it is common to tap into the events dispatched through the Models lifecycle. There are a few different ways you can do this, and in this tutorial, I will walk through them and explain the benefits and drawbacks of each one.

I will use the same example for each approach so that you can see a direct comparison. This example will assign the model's UUID property to a UUID during the creation of the model itself.

Our first approach uses the model's static boot method to register the behavior. This allows us to work directly on the model and register the callback we want to run when the model is being created.

declare(strict_types=1);
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
 
class Office extends Model
{
public static function boot(): void
{
static::creating(fn (Model $model) =>
$model->uuid = Str::uuid(),
);
}
}

This approach is perfectly fine for small and straightforward reactions to model events like adding a UUID, as it is pretty easy to understand, and you can see exactly what is going on on the model. The biggest issue with this approach is code repetition, and if you have multiple models needing to assign UUIDs, you will do the same thing repeatedly.

This leads us nicely onto the second approach, using a trait. In Laravel, your models can inherit traits and automatically boot them if you create a method on your trait that starts with boot and ends with the trait name. Here is an example:

declare(strict_types=1);
 
namespace App\Models\Concerns;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
 
trait HasUuid
{
public static function bootHasUuid(): void
{
static::creating(fn (Model $model) =>
$model->uuid = Str::uuid(),
);
}
}

Using a trait allows you to add this behavior to each model that requires it and is easy to implement. My most significant drawback is that stacking these behaviors can cause issues when multiple traits want to tap into the same model event. They begin fighting for priority and can get messy pretty quickly.

This leads us to the next option, Model Observers. Model Observers are a class-based approach to reacting to model events, where the methods correspond to the specific events being fired.

declare(strict_types=1);
 
namespace App\Observers;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
 
class OfficeObserver
{
public function creating(Model $model): void
{
$model->uuid = Str::uuid();
}
}

This class will need to be registered somewhere, in a Service Provider or the Model itself (this is where I recommend it). Registering this observer in the model provides visibility on the model level to the side effects that change the eloquent behavior. The problem with hiding this away in a Service Provider is that unless everyone knows it is there - it is hard to know about. The biggest drawback of this approach is its visibility. In my opinion, this approach is fantastic when used correctly.

One more way you could approach this problem is to take advantage of the $dispatchesEvents property on the Eloquent Model itself. This is a property on every Eloquent Model that allows you to list the events you want to listen for and a class called for these events.

declare(strict_types=1);
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
 
class Office extends Model
{
protected $dispatchesEvents = [
'creating' => SetModelUuid::class,
];
}

The SetModelUuid will be instantiated during the lifecycle of the Eloquent model and is your chance to add behavior and properties to the model.

declare(strict_types=1);
 
namespace App\Models\Events;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
 
class SetModelUuid
{
public function __construct(Model $model)
{
$model->uuid = Str::uuid();
}
}

This approach is one of the cleanest and easiest to understand, as there is plenty of visibility on the model, and you can easily share this class across models. The biggest issue you will face is if you need to trigger multiple actions on a model event.

In conclusion, in all honesty, there is no right way to do this. You can choose any of the above methods, and they will work, but you should choose the one that is right for you and your specific use case. I would like to see more options around this particular functionality.

For example, an observer is a good option if you need to add multiple properties to a model on model events. However, is it the best option? How about if we used the dispatch events property to run a custom pipeline for that model?

declare(strict_types=1);
 
namespace App\Models\Pipelines;
 
use App\Models\Office
 
class OfficeCreatingPipeline
{
public function __construct(Office $model)
{
app(Pipeline::class)
->send($model)
->through([
ApplyUuidProperty::class,
TapCreatedBy::class,
]);
}
}

As you can see, we can start to use pipelines to add multiple behaviors to model events. Now, this isn't tested, so I do not know 100% if it would work - but as a concept, it could open up a composable approach to reacting to model events.

How do you handle model events in your Laravel projects? Let us know on Twitter!

Steve McDougall photo

Educator and Content creator, freelance consultant, API evangelist

Cube

Laravel Newsletter

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

image
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article
MongoDB Vector Search in Laravel: Finding the Unqueryable image

MongoDB Vector Search in Laravel: Finding the Unqueryable

Read article
Laravel Cloud Adds “Markdown for Agents” to Serve AI-Friendly Content image

Laravel Cloud Adds “Markdown for Agents” to Serve AI-Friendly Content

Read article
Laravel Releases Nightwatch MCP Server for Claude Code and AI Agents image

Laravel Releases Nightwatch MCP Server for Claude Code and AI Agents

Read article