Home / Snippets / How to Disable Mass Assignment For All Model in Laravel
How to Disable Mass Assignment For All Model in Laravel cover

How to Disable Mass Assignment For All Model in Laravel

1.2K

3 years ago

0 comments

Sometimes you might want to disable mass assignment protection in Laravel and to do that you have to call the "unguard()" method of the base Model class.
Model::unguard();
The above code should be called from the "boot" method of the "AppServiceProvider" class.
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Model::unguard();
    }
}
By having this "unguard" method called, you will have to make sure that any data that come into the Laravel be validated before storing it into the database.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([/* validate your fields here */]);
    }
}
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this