We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
It's a good practice to disable lazy-loading in your Laravel code when running in development (or testing) mode. This will help you avoid N+1 problems.
You can easily do this by adding the following to your AppServiceProvider::boot
function:
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Model::preventLazyLoading(App::environment('local', 'testing'));
}
public function register()
{
}
}
There's one drawback though, it's all or nothing. When you are working with an existing codebase and you want to gradually fix the issues, you might need to (temporarily) disable the check for certain models and / or relations.
To do so, you can register a closure using Model::handleLazyLoadingViolationUsing
to customize the check
namespace App\Providers;
use App\Domains\User\CompanyUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation): void {
if ($model instanceof CompanyUser) {
if ($relation === 'offices') {
return;
}
}
throw new LazyLoadingViolationException($model, $relation);
});
Model::preventLazyLoading(App::environment('local', 'testing'));
}
public function register()
{
}
}
In the above example, we no longer throw the lazy-loading error when loading the offices
relation on the model CompanyUser
.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.