Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Model::unguard() do in the database seeder file from Laravel 5?

Tags:

php

laravel-5

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.

like image 731
Rohan Avatar asked Sep 26 '15 09:09

Rohan


People also ask

What is the use of database seeder in Laravel?

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.

What is model in Laravel?

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.


2 Answers

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.

like image 187
peaceman Avatar answered Oct 06 '22 03:10

peaceman


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
like image 36
Akongnwi Devert Avatar answered Oct 06 '22 02:10

Akongnwi Devert