It is good practice to always load relational data with eager loading in laravel application. But sometimes we forgot to eager relational data with our query. What if we get an exception if we do not eager load our eloquent relationship in laravel? Yes, we can do this by using the preventLazyLoading() method. 

So in this tutorial, we will see how to prevent lazy loading in laravel application in a laravel way. We will also see we can disable lazy loading in production mood.

prevent-lazy-loading

So let's see the example code of how to prevent lazy loading in laravel:

App\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Model::preventLazyLoading();
    }
}

 

This condition will work everywhere. Now assume we want to disable it in production. So we can do it very easily. The preventLazyLoading method accepts an optional boolean parameter that indicates if lazy loading should be prevented. 

App\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Model::preventLazyLoading(! $this->app->isProduction());
    }
}

 

Read also: How To Limit Eloquent Relationship Result In Laravel?

 

Conclusion

In this prevent lazy loading laravel tutorial,  I have tried my best to let you know how to prevent lazy loading in laravel. Hope now after completing this prevent lazy loading model relationship laravel tutorial, you will know force eager loading in laravel.