CONFIGURING ELOQUENT STRICTNESS
Jan 07, 2024 Copy Link
When we are working on a project in a Local Environment we may commit such these mistakes
1. Try showing data with a 1 + N query problem
Laravel does not inspire you when you are using a LazyLoading
feature but, you can write only one single line of code in the `AppServiceProvider.php`
class to customize that behavior:
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Model::preventLazyLoading();
}
2. Try accessing non-existing attributes
Laravel also will not throw an exception when you try to get an attribute that does not exist in the `select`
statement and to tell Laravel to start throwing an exception you should write just a single line of code with the previous one:
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Model::preventLazyLoading();
Model::preventAccessingMissingAttributes();
}
3. Try filling in a non-fillable attribute
We know that the Eloquent Models
comes with a protected `fillable`
property which represents a white list of allowed attributes when we create a new instance, but what if you accidentally try to save an attribute that does not exist in that list, Laravel will do nothing but also you can bespoke that by adding a single line of code again:
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Model::preventLazyLoading();
Model::preventAccessingMissingAttributes();
Model::preventSilentlyDiscardingAttributes();
}
We handled all these scenarios now but, let's refactor the previous code:
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Model::shouldBeStrict($this->app->isProduction());
}
The code became more clean now 🧼