Preventing N+1 Issues

  • Laravel
  • Eloquent

If you ever want to prevent N+1 issues, you can have Laravel throw an error when you try to access a relationship thats not eagar loaded:

1namespace App\Providers;
2 
3use Illuminate\Database\Eloquent\Model;
4use Illuminate\Support\ServiceProvider;
5 
6class AppServiceProvider extends ServiceProvider
7{
8 public function boot(): void
9 {
10 Model::preventLazyLoading();
11 }
12}

This will throw an error:

1Attempted to lazy load [user] on model [App\Models\Post] but lazy loading is disabled.