Laravel tips
5 tips · newest first
Short, practical Laravel tips: Eloquent performance, queues, testing helpers, and framework features most codebases underuse. Each tip is a copy-pasteable snippet with the why behind it.
Attach request-scoped metadata with the Context facade so it flows into logs and jobs
LARAVELThe Context facade (Laravel 11+) stores key/value data for the current request that's automatically added to every log…
Turn N+1 queries into errors in development with preventLazyLoading()
LARAVELCalled in a service provider, this throws a LazyLoadingViolationException whenever a relation is accessed without being…
Lock down outbound HTTP in tests with preventStrayRequests()
LARAVELHttp::fake() alone lets un-matched requests fall through to the real network, which makes tests flaky and slow and can…
Auto-delete stale records with the Prunable trait instead of a custom command
LARAVELAdd Prunable and a prunable() query, and model:prune (scheduled) deletes matching rows in chunks — no bespoke cleanup c…
Use whenLoaded() in API resources to avoid firing queries during serialization
LARAVELReferencing $this->posts directly in a resource lazy-loads the relation for every model when it wasn't eager-loaded — a…