Laravel Observers: Cleaner Model Side-Effects

When a model save needs to trigger side-effects, observers are cleaner than overriding boot methods. Here's a working pattern with examples.

Richard GamoraRichard GamoraFullstack developer·3 min read
LaravelEloquentArchitecture

When a model is saved, deleted, or restored, you often need a side-effect to happen — clear a cache, write an audit log, fire a notification. The model's boot() method works, but it gets crowded fast. Observers are the cleaner pattern.

What an observer is

An observer is a class with methods named after Eloquent events: created, updated, deleted, restored. You register it with Order::observe(OrderObserver::class) and Laravel calls the matching method whenever that event fires on an Order model.

phpclass OrderObserver
{
    public function created(Order $order): void
    {
        SendOrderReceipt::dispatch($order);
        Cache::tags('orders')->flush();
    }

    public function deleted(Order $order): void
    {
        AuditLog::record('order.deleted', $order);
    }
}

Why this is better than boot()

Putting all your event handling in static::created(...) inside the model itself works, but the model file balloons and the side-effects bury the actual model definition. With an observer, the model stays focused on data, and the side-effects live somewhere named after what they are.

It is also easier to test. You can mock the observer entirely in tests where you do not care about the side-effects, or assert that an observer's method was called when you do.

Where observers go wrong

Observers fire on every save, including saves from seeders, factories, and tests. A heavy side-effect that runs in tests will slow your suite down or break it entirely. Make every observer method check whether it should actually run — or use $model->saveQuietly() in places where you know you do not want it.

About the author

Richard Gamora

Richard Gamora

Fullstack developer based in the Philippines, working mostly with Laravel and Vue.js, with eight years of production experience across web and mobile.

me@richardgamora.comUpwork ↗

More on Laravel