DEV Community

Morcos Gad
Morcos Gad

Posted on

Prevent Lazy Loading - Laravel

Today we will talk about Prevent Lazy Loading and how it affects the performance of the application. Let's find out in the next example
We have a binding relationship in the model User

public function logins()
{
   return $this->hasMany(Login::class);
}
Enter fullscreen mode Exit fullscreen mode

Here we bring all users with login

$users = User::get();
foreach ($users as $user){
   foreach($user->logins as $login){
      dd($login)
   }
}
Enter fullscreen mode Exit fullscreen mode

in app/Provider/AppServiceProvider.php
$this->app->isProduction() if App in Production

use Illuminate\Database\Eloquent\Model;

public function boot()
{
    Model::preventLazyLoading(! $this->app->isProduction());
}
Enter fullscreen mode Exit fullscreen mode

Now bring all users with login Use Laravel Debugbar https://github.com/barryvdh/laravel-debugbar You will see the difference between before and after using preventLazyLoading

$users = User::with(['logins'])->get();
foreach ($users as $user){
   foreach($user->logins as $login){
      dd($login)
   }
}
Enter fullscreen mode Exit fullscreen mode

I hope you liked the code and benefited from it. For more information, visit these links
https://laravel.com/docs/8.x/eloquent-relationships#preventing-lazy-loading
https://www.youtube.com/watch?v=PeaMgcJgQIk

Oldest comments (0)