Bypassing Mass Assignment Protection in Laravel

Eloquent models have a great feature called Mass Assignment Protection. This feature skips unwanted attributes when creating or updating a model. This is useful to pass an array of attributes to the model and filter only the ones that you want to be stored. For instance, let’s say you have a field is_admin in the User model, if this attribute is not set in the $fillable array, then it will not be stored.

Model attributes can always be set directly as in $user->is_admin = true;

Disable Mass Assignment Protection

Sometimes it is useful to bypass mass assignment protection for things like database seeders or commands. In these cases, it is better to disable the protection on demand, than to keep the attributes exposed. The proper way to do that is by using the static methods unguard() and reguard() on the Model.


Please, be aware that this method is dangerous, and should only be used when absolutely necessary.

These are the method definitions inside the Eloquent Model:

Share Post :