Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Allow mass assignment for all the models in Laravel

While it’s not recommended to allow all of your model’s attributes mass assignable since in that case you need to make sure to hand-craft the arrays passed to Eloquent’s fill, create, and update methods.

But there might be some instances where you may want to consider unguarding all of the attributes.

The de-facto way of unguarding a single model is to set an empty array to the $guarded property like so.

protected $guarded = [];

But what if you want to make all of your models as mass assignable all at once? How would you do that?

Well, to do that, you need to use the unguard() method on the Illuminate\Database\Eloquent\Model class. This can be done in the boot method of the applications’s AppServiceProvider like so.

<?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()
    {
       Model::unguard();
    }
}

That’s it! This will make all your models mass assignable from a single place.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?