Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 67 ยท Eloquent ORM

Model Events, Observers and Soft Deletes

React to Eloquent model lifecycle events with observers, keep deleted rows recoverable with SoftDeletes, prune old data, and use UUID or ULID primary keys.

Models have a life: they are created, updated, saved, deleted and sometimes restored. Eloquent announces each of those moments as an event, so you can attach behaviour without scattering it through controllers: generate a slug before a post is created, clear a cache after it is saved, refuse to delete an account that still owns invoices. This lesson covers those model events, how to organise them in observers, and the closely related feature of soft deletes, where "delete" means "hide, but keep". It finishes with pruning old rows and with UUID and ULID keys.

It assumes you know Eloquent models and CRUD and the general idea of events and listeners. As elsewhere, Laravel itself cannot run on this site, so the real code is read-only and the runnable code consists of plain PHP stand-ins.

The lifecycle events

Eloquent fires these events around persistence:

When Events
A model is loaded from the database retrieved
First save (INSERT) saving, creating, then created, saved
Later save (UPDATE) saving, updating, then updated, saved
Delete deleting, then deleted
Soft delete extras trashed, restoring, restored, forceDeleting, forceDeleted

The present-tense events (saving, creating, updating, deleting) fire before the SQL runs, and a listener can stop the operation by returning false. The past-tense ones fire afterwards. saving and saved surround both creates and updates, so they are the right place for logic that applies to every write.

The quickest way to hook one is a closure in the model's booted() method:

PHP
class Post extends Model
{
    protected static function booted(): void
    {
        static::creating(function (Post $post) {
            $post->slug ??= Str::slug($post->title);
        });

        static::deleting(function (Post $post) {
            if ($post->comments()->exists()) {
                return false;       // cancel the delete
            }
        });
    }
}

Observers

Closures in booted() become crowded fast. An observer is a class with one method per event, which keeps all the lifecycle behaviour of a model in one place:

PHP
// php artisan make:observer PostObserver --model=Post
class PostObserver
{
    public function creating(Post $post): void
    {
        $post->slug ??= Str::slug($post->title);
    }

    public function saved(Post $post): void
    {
        Cache::forget("post.{$post->id}");
    }
}

use Illuminate\Database\Eloquent\Attributes\ObservedBy;

#[ObservedBy([PostObserver::class])]
class Post extends Model {}

The #[ObservedBy] attribute registers the observer; you can also call Post::observe(PostObserver::class) in a service provider. If an observer does something that must only happen after the surrounding database transaction commits (sending a notification, dispatching a job), implement the ShouldHandleEventsAfterCommit interface so it does not fire for a transaction that later rolls back.

For event classes you can map model events in the $dispatchesEvents property, so that created dispatches your own PostCreated event with its own listeners.

What does not fire events

This is the most common surprise. Events are fired by the model instance methods save(), create(), update() and delete(). A mass query such as Post::where('views', 0)->update([...]) or ->delete() goes straight to the database and fires no model events for the affected rows, because Eloquent never loads those models. The same applies to insert(), upsert() and raw queries. If an observer must run, load the models first, or accept that bulk operations bypass it.

To save without firing events on purpose (a data migration, a cache warm-up), use $post->saveQuietly(), $post->deleteQuietly(), or wrap code in Model::withoutEvents(fn () => ...).

Use events sparingly

Observers are convenient and invisible. A developer who writes $post->save() cannot see that a slug is generated, a cache cleared and a webhook sent. Keep observers small and predictable: derive values, keep caches in sync, write audit rows. For multi-step business processes, call an explicit action or service class instead (see architecture patterns), and for slow work dispatch a queued job from the observer.

The following stand-in implements the lifecycle ordering, cancelling by false, observers and the "quiet" save, so you can watch the order of events:

PHP A model with lifecycle events, an observer and quiet saves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the output: creating ran only for the first save and generated the slug, saved ran for both, and the quiet save printed only its SQL line. The locked post survived because the deleting listener returned false.

flowchart TD
    A["$post->save()"] --> B["saving"]
    B --> C{"exists?"}
    C -->|"no"| D["creating"]
    C -->|"yes"| E["updating"]
    D --> F["INSERT"]
    E --> G["UPDATE"]
    F --> H["created"]
    G --> I["updated"]
    H --> J["saved"]
    I --> J

A listener that returns false from saving, creating or updating stops the save before any SQL runs.

Soft deletes

A hard delete removes the row for good. Often that is wrong: users ask for their post back, accounting needs the history, and a foreign key from another table should not dangle. Soft deleting keeps the row and marks it with a timestamp in a deleted_at column instead.

PHP
// migration
$table->softDeletes();

// model
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
}

$post->delete();                         // sets deleted_at, row stays
$post->trashed();                        // true
Post::all();                             // hides soft-deleted rows (a global scope!)
Post::withTrashed()->get();              // everything
Post::onlyTrashed()->get();              // only the deleted ones
$post->restore();                        // deleted_at back to null
$post->forceDelete();                    // really remove the row

Under the hood the trait adds a global scope (the same mechanism from querying with Eloquent) that appends where deleted_at is null to every query. That explains the gotchas. Raw DB::table() queries still see deleted rows. A unique index does not know about soft deletes, so a deleted user's email still blocks a new signup unless you handle it (a partial index, or a rule such as Rule::unique('users')->withoutTrashed()). Cascading deletes at the database level do not run for soft deletes, so related rows stay too. And soft-deleted personal data is still personal data: for privacy requests you need to force-delete it.

Pruning old data

Rows rarely need to live forever. The Prunable trait lets a model describe which rows are stale, and the model:prune command, scheduled daily (see task scheduling), deletes them:

PHP
use Illuminate\Database\Eloquent\Prunable;

class Post extends Model
{
    use SoftDeletes, Prunable;

    public function prunable(): Builder
    {
        return static::onlyTrashed()->where('deleted_at', '<=', now()->subDays(30));
    }
}

// routes/console.php
Schedule::command('model:prune')->daily();

Prunable loads and deletes each model, so events fire and a pruning() method can clean related files first. MassPrunable deletes in bulk with one query per chunk and no events, which is much faster for huge tables such as logs.

UUID and ULID keys

By default the primary key is an auto-incrementing integer. It leaks information (/orders/1042 reveals your order volume and invites guessing) and is awkward when records are created on several servers. You can use UUIDs or ULIDs instead:

PHP
use Illuminate\Database\Eloquent\Concerns\HasUuids;   // or HasUlids

class Order extends Model
{
    use HasUuids;
}

// migration
$table->uuid('id')->primary();      // or $table->ulid('id')->primary();

Both traits generate the key when the model is created. In current Laravel, HasUuids produces ordered UUIDs (version 7), and HasVersion4Uuids gives purely random ones. ULIDs are 26-character, URL-friendly and sortable by creation time. Time-ordered keys matter for performance: random keys scatter inserts across the whole index, while time-ordered keys append near the end, as integers do. The trade-off for any of them is size: 16 bytes instead of 4 or 8, in every index and foreign key.

Here is a stand-in that combines soft deletes with a sortable, time-prefixed id. The ids are deterministic here (a fixed clock and a counter); real ULIDs add randomness:

PHP Soft deletes, restore and sortable ids on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The soft-deleted row vanishes from the default list, appears in withTrashed, comes back after restore, and is gone for good after pruning.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about model events is true?

    The present-tense events fire before persistence and returning false stops it. Mass queries bypass models entirely, so they fire no events.
  2. 2. What does the SoftDeletes trait do when you call delete() on a model?

    The row stays; a global scope adds where deleted_at is null to ordinary queries, and withTrashed or onlyTrashed change that.
  3. 3. A user soft-deletes an account and tries to register again with the same email, but a unique index blocks it. Why?

    The database does not know about the soft delete. You need a rule or index that accounts for deleted rows, or you must force-delete the old row.
  4. 4. Why might you prefer ULIDs or ordered UUIDs to random UUIDs as primary keys?

    Time-ordered keys keep index inserts efficient, while fully random keys scatter writes across the whole index.

Summary

  • Eloquent fires retrieved, saving/saved, creating/created, updating/updated and deleting/deleted events; the present-tense ones can cancel an action by returning false.
  • Observers (#[ObservedBy]) group a model's lifecycle logic in one class; saveQuietly() and Model::withoutEvents() skip events.
  • Mass updates, deletes and raw queries never fire model events.
  • SoftDeletes stores deleted_at, hides trashed rows through a global scope, and offers withTrashed(), onlyTrashed(), restore() and forceDelete(); mind unique indexes, cascades and privacy.
  • Prunable with the scheduled model:prune command removes stale rows; HasUuids and HasUlids give non-guessable, sortable keys.

Next: Collections