Strict Mode in Laravel

 

When starting a new Laravel application, using the `Model::shouldBeStrict()` method can help enforce strict mode for your Eloquent models. Strict mode in Eloquent provides additional safeguards by throwing exceptions for common pitfalls, such as attempting to access an undefined attribute or mutating a missing attribute. This can help catch bugs early in the development process.


Here is a step-by-step guide on how to enable and use strict mode in a new Laravel application:


1. Create a New Laravel Project


First, create a new Laravel project if you haven't already:


composer create-project --prefer-dist laravel/laravel new-app

cd new-app


2. Enable Strict Mode for Eloquent Models


To enable strict mode globally for all models in your Laravel application, you can modify the `AppServiceProvider`.


#### Update `AppServiceProvider`


Open the `App\Providers\AppServiceProvider` class and update the `boot` method to enable strict mode for all Eloquent models:


<?php


namespace App\Providers;


use Illuminate\Support\ServiceProvider;

use Illuminate\Database\Eloquent\Model;


class AppServiceProvider extends ServiceProvider

{

    /**

     * Bootstrap any application services.

     *

     * @return void

     */

    public function boot()

    {

        // Enable strict mode for all Eloquent models

        Model::shouldBeStrict();

    }


    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }

}


This code will enable strict mode for all models globally when the application boots.


3. Testing Strict Mode


To see strict mode in action, you can create a simple model and try to access or set an undefined attribute.


#### Create a Model and Migration


Create a new model and migration:


php artisan make:model Product -m


This will create a `Product` model and a migration file. Update the migration file to add some fields:


// database/migrations/xxxx_xx_xx_create_products_table.php


use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;


class CreateProductsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('products', function (Blueprint $table) {

            $table->id();

            $table->string('name');

            $table->decimal('price', 8, 2);

            $table->timestamps();

        });

    }


    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('products');

    }

}


Run the migration:


php artisan migrate


Testing Undefined Attributes


Now, let's test accessing and setting undefined attributes in strict mode.


use App\Models\Product;


// Create a new product

$product = new Product();

$product->name = 'Test Product';

$product->price = 99.99;

$product->save();


// Try to access an undefined attribute

try {

    $undefinedAttribute = $product->undefined_attribute;

} catch (Exception $e) {

    echo "Exception caught: " . $e->getMessage();

}


// Try to set an undefined attribute

try {

    $product->undefined_attribute = 'value';

} catch (Exception $e) {

    echo "Exception caught: " . $e->getMessage();

}


When you run this code, you should see exceptions being thrown when trying to access or set undefined attributes, demonstrating that strict mode is working correctly.


By using `Model::shouldBeStrict()`, you can ensure your Eloquent models are used correctly and catch common mistakes early in the development process.