Selectively Disable Laravel Strict Mode

June 13, 2023

About a year ago, Laravel added strict mode which lets you turn off some convenience features that can impact performance or introduce bugs if you're not careful. It's a great thing to enable by default in your non production environments so that your teams are following best practices. You can do so individually with these commands:

Model::preventLazyLoading();
Model::preventSilentlyDiscardingAttributes();
Model::preventsAccessingMissingAttributes();

If you'd like to enable them all, there is a shortcut method to so do:

Model::shouldBeStrict(! $this->app->isProduction());

Recently at work, we ran into a scenario where we wanted to disable strict lazy loading protection when pruning soft deleted models. We are using the shortcut to enable everything, but we were attempting to disable just the lazy loading with Model::preventLazyLoading(false);. It turns out that if you are enabling with the shortcut, you must disable with the shortcut as well otherwise it will have no effect.

So the solution was to do this in the pruning method on the model:

public function pruning(): void
{
    Model::shouldBeStrict(false);
    $this->relationshipName->each->prune();
    Model::shouldBeStrict(! $this->app->isProduction());
}

Hopefully that helps someone else with the same issue!

Monitor your DNS Zones with ZoneWatcher

Be alerted of DNS record changes moments after they happen, not from upset customers.

ZoneWatcher screenshot