Enable Model::shouldBeStrict() in development to automatically throw exceptions on lazy loading, unfillable attributes, and missing model properties.
In development environments, subtle bugs like lazy loading (N+1 query problems), mass-assigning unguarded attributes, or accessing misspelled model attributes can easily slip into production undetected.
Calling Model::shouldBeStrict() enables three strict development safeguards in a single call.
Enabling Strict Mode
Add the check inside AppServiceProvider::boot():
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Enable strict checks in local and testing environments
Model::shouldBeStrict(! $this->app->isProduction());
}
}
What shouldBeStrict() Enforces
- **Prevents Lazy Loading (
preventLazyLoading)**: Throws aLazyLoadingViolationException` whenever a relationship is loaded outside an eager-loading query, eliminating N+1 performance bottlenecks. - **Prevents Silently Discarding Attributes (
preventSilentlyDiscardingAttributes)**: Throws aMassAssignmentExceptionif you pass fields tocreate()orupdate()that are not defined in$fillable`. - **Prevents Accessing Missing Attributes (
preventAccessingMissingAttributes)**: Throws aMissingAttributeExceptionif you attempt to read an attribute that was excluded from a partialselect('id', 'name')` query.
Summary
- Catches N+1 query regressions immediately during development and test suites.
- Prevents silent data loss caused by misconfigured
$fillablearrays. - Zero performance impact in production when conditioned on
! $this->app->isProduction().
Tags:
Laravel Eloquent Performance Debugging