Avoid Silent Failures in Laravel Using preventLazyLoading()
The Hidden Problem: Lazy Loading
In Laravel applications, this looks harmless:
$users = User::all();
foreach ($users as $user) {
echo $user->roles->count();
}
But behind the scenes:
👉 It runs N+1 queries
👉 One query for users + one per user for roles
This silently kills performance.
The Solution: preventLazyLoading()
Laravel gives you a way to detect this early.
Enable It
In AppServiceProvider:
use Illuminate\Database\Eloquent\Model;
public function boot()
{
Model::preventLazyLoading(! app()->isProduction());
}
What Happens Now
If you accidentally do lazy loading:
$user->roles;
Laravel will:
- Throw an exception (or warning)
- Alert you during development
The Correct Way
Use eager loading:
$users = User::with('roles')->get();
Now:
- Only 2 queries
- No performance issue
Why This Is Powerful
It helps you:
- Catch performance bugs early
- Avoid hidden N+1 issues
- Improve query efficiency
- Build production-ready apps
When to Use It
Use it:
- In development environment
- While building APIs
- When optimizing queries
Avoid enabling it in production.