CONFIGURING ELOQUENT STRICTNESS

Jan 07, 2024 Copy Link

When we are working on a project in a Local Environment, we may commit such 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-existent 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 you can customize 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 has become cleaner now 🧼

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autol...

    FREE

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE