Eloquent Model Events: Ordering
Eloquent Model Events: Ordering
Eloquent Model Events: Ordering
Tip: Event Order
retrieved- after fetchcreating/updating- before savecreating/updated- after savesaving/saved- wraps bothdeleting/deleted- around delete
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)