Disable Lazy loading in Laravel

Laravel provides automatic Eager loading by default. When Eloquent relationships are accessed as properties the relationship data is not loaded until you access the property for the first time. Eager loading can cause multiple query issue so you might need to disable it sometimes. You may need to eager load relationship after the parent model has already been retrieved. Lazy loading delays loading or initialisation of resources until they are actually needed. It reduces initial load time and it conserves bandwidth. First check if the relationship is loaded.

foreach ($posts as $p) {

if ($p->relationLoaded('author')) echo $p->author->name;

}

Their is a package to disable Lazy load it actually creates a Trait to override the getRelationshipFormMethod. You can install the package using composer.

composer require ybaruchel/laravel-disable-lazyload


<?php


namespace App\Traits;


trait DisableLazyLoad

{

public function getRelationshipFromMethod($method)

{

throw new\BadMethodCallException('Relation lazy load has been disabled for performance reasons.');

}

}

Then the Trait is used in the Model as shown below.

<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;

use App\Traits\DisableLazyLoad;


class Post extends Model

{


use DisableLazyLoad;


}