$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[October 29, 2026] Eloquent ORM

Eloquent Model Events: Ordering

Eloquent Model Events: Ordering

────────────────────────────────────────────────────────

Eloquent Model Events: Ordering

Tip: Event Order

  1. retrieved - after fetch
  2. creating / updating - before save
  3. creating / updated - after save
  4. saving / saved - wraps both
  5. deleting / deleted - around delete
  6. Gotcha: saving Fires Before creating

    saving fires on both create and update, before the specific event.

    Tip: Cancel with false

    static::creating(function ($post) {
        if (!$post->isValid()) return false;
    });
    

    Gotcha: saved vs created

    saved fires on both create and update. Use created for new records only.

    Tip: Event Priority

    Register listeners in the order you want them to execute.

    Gotcha: retrieved Event

    Fires every time a model is fetched. Can be expensive for large queries.

    Tip: Use cursor() for Memory-Neutral Iteration

    When exporting 100K rows, get() loads everything into memory. cursor() uses yield and keeps memory flat regardless of row count. Perfect for artisan commands.

    Tip: whereHas() vs load() — Two Different Things

    whereHas() filters the parent query by relationship existence. load() eager-loads relationships AFTER the query. Mixing them up is a common source of logic bugs.

    Gotcha: withCount() Adds a Subquery

    withCount('comments') runs a correlated subquery on every row. On large tables, this can be slower than a separate query. Profile before relying on it.

    Senior Insight

    Model events are powerful but they execute in the same transaction as the triggering operation, which means a failing event listener can roll back a legitimate database operation. I've seen creating events that validate data inconsistently with Form Requests, leading to confusing errors. My practice: use model events only for cross-cutting concerns (like generating slugs or setting default values), and keep validation in Form Requests where it belongs.

    Source: Laravel Docs (https://laravel.com/docs/eloquent), Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/eloquent)

────────────────────────────────────────────────────────
<-- back to posts