Use Model shouldBeStrict when starting a new Laravel app - TechvBlogs

Use Model shouldBeStrict when starting a new Laravel app

Explore the power of Laravel's shouldBeStrict model validation for a robust and secure foundation in your new Laravel app. Learn how this feature ensures strict data integrity, enhancing the reliability of your application from the start.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

1 month ago

TechvBlogs - Google News

Once you've conceptualized a new app and set up Laravel, what should be your initial step to begin development?

In my case, I access the app service provider, navigate to the boot method, and configure the global Model::shouldBeStrict():

public function boot(): void
{
    Model::shouldBeStrict();
}

Enabling this feature results in the following actions:

public static function shouldBeStrict(bool $shouldBeStrict = true)
{
    static::preventLazyLoading($shouldBeStrict);
    static::preventSilentlyDiscardingAttributes($shouldBeStrict);
    static::preventAccessingMissingAttributes($shouldBeStrict);
}

Enabling this functionality encompasses three key actions:

  1. Prevents lazy loading.
  2. Avoids silently discarding attributes.
  3. Blocks access to missing attributes.

Preventing Lazy Loading

Here's an example illustrating lazy loading:

$articles = \App\Models\Article::get();
 
foreach ($articles as $article) {
     echo "<li>" . $article->user->name . "</li>\n";
}

Executing this code will yield the expected output. Nevertheless, it triggers lazy loading for the user relationship, leading to a new query for each iteration in the loop.

Enabling shouldBeStrict instead of executing the code will result in an error, providing immediate feedback.

Attempted to lazy load [user] on model [App\Models\Article] but lazy loading is disabled.

Prevent Silently Discarding Attributes

Here's an example demonstrating an attempt to update an attribute that is not fillable:

$user->fill(["remember_token" => "bar"]);

Now, executing this will result in an exception being thrown:

Add fillable property [remember_token] to allow mass assignment on [App\Models\User].

Prevent Accessing Missing Attributes

Let's consider a scenario where we attempt to display a property on the User that may not exist:

{{ $user->nonexistant }}

By default, Laravel will simply not display anything if the property is not found. However, with Strict mode turned on, you will receive:

The attribute [nonexistant] either does not exist or was not retrieved for model [App\Models\User].

This proves particularly beneficial in cases where a spelling mistake is made, such as:

{{ $user->emial }}

 Enabling Model::shouldBeStrict() provides instant feedback in case of errors, helping to catch mistakes early. It has become my initial step in every app, serving as a preventive measure against basic errors that could potentially harm the app later on.

Comments (0)

Comment


Note: All Input Fields are required.