Avoid Mass Assignment to Set Unguard Globally For Every Model In Laravel

Hello devs in this quick laravel tips tutorial i will show you a nice tips which will be very essential for you i hope. Look, when we submit a  form then we set fillable property in those model or set an empty guarded array. 

But do you know that you can set globally guarded for you all model. We can unguard all your Models instead of setting the protected guarded variable to an empty array in each App\Models\YourModel class using Model::unguard() in the boot method of AppServiceProvider class.

app\Providers\AppServiceProvider.php

namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{
 /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(){
     
        Model::unguard();
    }


}

 

Now after doing that, no need to define your fillable property or set an empty guarded array like

protected $fillable = [
        'backup_path'
];

//or

protected $guarded = [];

 

Read also : Laravel 8.x Vue Component with Datatable Example

 

Hope it can help you.