dongya9904 2014-07-22 01:19
浏览 11
已采纳

Laravel Mass Assignment Issue似乎不一致

I am working on implementing some Models in Laravel 4. When attempting to create a new Instance of a model, I receive a MassAssignmentException. From my research, I have learned that by default, all fields are considered guarded. In order to get this to work, I need to specify the fillable fields. Once I do that, it works fine.

However, during database seeding, I am creating some new objects using the same methods with no fillable attribute specified and I do not receive the MassAssignmentException? This is what makes no sense. Am I missing something here?

Code which threw the MassAssignmentException before I added the fillable var:

Role::create(array(
    'name' => 'admin'
));

Code in DatabaseSeeder which did not throw the Exception with no fillable var:

Company::create(array(
    'name' => 'ABC Toys Inc.'
));

Anyone know the reason for this?

  • 写回答

1条回答 默认 最新

  • dpb35161 2014-07-22 01:47
    关注

    The DatabaseSeeder class which is included in Laravel (which I assume you are using) has the Mass Assignment guarding switched off by default.

    class DatabaseSeeder extends Seeder 
    {
    
        public function run()
        {
            Eloquent::unguard();
        }
    }
    

    The Eloquent::unguard() function switches off mass assignment guarding.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?