Unguard Laravel Model

Unguard model for Testing or Seeding

Panjeh
1 min readJan 26, 2021

First have a look at :

https://laravel.com/docs/8.x/eloquent#mass-assignment

for more information about mass assignment in Eloquent.

In fact, Model::unguard() does temporarily disable the mass assignment protection of the model, so you can seed all model properties while they are not fillable!

If you have a look at User model for example you see only some of the properties are only fillable. Here user->id is not fillable.

When you are testing your code somewhere you need to make a user like

new User( [ 'id' = 1, 'email'=> 'John@gmail.com', 'password'=> 123])

Since id is not fillable you are not allowed to do that so you need first unguard your model against mass assignment.

So before making the user you need to do :

User::unguard();

It is a good practice to reguard the mode just after you create one object from that model, like:

Model::reguard()

I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

Responses (1)