Model::unguard()
does temporarily disable the mass assignment protection of the model, so you can create records without worrying about the fillable. It’s not recommended to it for the users, but only for specific task such as seeding etc.
For example,
We have a category
table in our application.
$table->double('name'); $table->boolean('status')->default(false);
And in the model Category
protected $fillable = [ 'name', ]
When you try the below code, it will insert the category status as false, even though we have set the status as true. In another way, it will not consider the status field as an entry in the array as it’s not in the fillable array.
Category::create([ 'name' => "Sports", 'status' => true ])
To overcome this we can use like this
Model::unguard(); Category::create([ 'name' => "Sports", 'status' => true ]) Model::reguard();
This will temporarily disable the amazing security feature, and reenable it after our execution.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply