framework: Reguard model in seeding not working

  • Laravel Version: 5.4.19

Description:

  • Trying to enable $fillable and $guard attributes on all model in seeding.
  • For that, trying to write Illuminate\Database\Eloquent\Model::reguard() in method run before start seeding in main class DatabaseSeeder.
  • And occur exception Illuminate\Database\Eloquent\MassAssignmentException on field, which present on $fillable attribute.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 22 (4 by maintainers)

Most upvoted comments

Test repo: https://github.com/RikSomers/SeederTest

I followed your steps:

  • Make the model with migration (php artisan make:model SomeModel -m)
  • Change migration to contain name field
  • Fill the fillable array with ‘name’
  • Run migrations (php artisan migrate)
  • Copy your seeder code
  • Run seeder (php artisan db:seed)

Can’t reproduce the error you’re getting.

Do you have some other application code that might be executed?

For example, you might have another model that gets created in the process of the seeder, which is given a ‘name’ attribute that is not mass assignable.

But attribute name exists in property $fillable on model!

Your code is working exactly like it should. Mass assignment is enabled and working properly when you call ‘reguard’. What do you expect to happen? By default, in seeders, mass-assignment is bypassed. When you add ‘reguard’, then an exception will be thrown if you try to assign a property that is not listed in your ‘fillable’ fields. Seems like you’re not understanding what mass-assignment protection is.

Either way, since this doesn’t appear to be a bug, it would probably be best to take it to larachat or [laracasts forums[(laracasts.com/discuss).

I use Model::reguard() method to enable mass assignment restrictions http://joxi.ru/l2ZVP4EHKDb42J

Code to reproduce

class SomeModel extends Illuminate\Database\Eloquent\Model
{
    protected $fillable = ['name'];
}

class DatabaseSeeder extends Illuminate\Database\Seeder
{
    public function run()
    {
        Illuminate\Database\Eloquent\Model::reguard();
        
        App\SomeModel::create([ 'id' => 100, 'name' => 'Foo' ]);
    }
}

After run php artisan db:seed i have exception Illuminate\Database\Eloquent\MassAssignmentException (name)