I am trying to find out what is the purpose of Model::unguard();
and Model::reguard();
in the DatabaseSeeder.php
file that ships with Laravel. I have gone through the seeding documentation at laravel's site and googled but in vain.
So what is the purpose of Model::unguard();
? Assuming Model::reguard();
is just the opposite.
Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.
Laravel Create Model is an MVC based PHP system. In the MVC architecture, 'M' stands for 'Model'. A model is used as a way for questioning data to and from the table within the database. Laravel gives a basic way to do that using Eloquent ORM where each table incorporates a Model to interact with it.
Model::unguard()
does temporarily disable the mass assignment protection of the model, so you can seed all model properties.
Take a look at http://laravel.com/docs/5.1/eloquent#mass-assignment for more information about mass assignment in Eloquent.
Take for example the currency table Migration file
$table->double('rate');
$table->boolean('is_default')->default(false);
If your Currency Model file, the only fillables are
protected $fillable = [
'rate',
]
is_default
can never be set by mass assignment. For example
Currency::create([
'rate' => 5.6,
'is_default' => true
])
will return a currency with
'rate' => 5.6
'is_default' => false
But you can mass assign the field using unguard and reguard as follows
Model::unguard()
Currency::create([
'rate' => 5.6,
'is_default' => true
])
Model::reguard()
Then your model will be created with
'rate' => 5.6
'is_default' => true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With