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);
}
Here we bring all users with login
$users = User::get();
foreach ($users as $user){
foreach($user->logins as $login){
dd($login)
}
}
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());
}
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)
}
}
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
Top comments (0)