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

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

Tags:

Php

Laravel 5