Search code examples
phplaravellaravel-4laravel-5mass-assignment

updateOrCreate - Mass Assignment Exception in Laravel


I'm working on a CRUD part of my system. Users' can update Keywords. What I'd like to do is similar to an INSERT IGNORE MySQL statement.

I am in an foreach loop and trying to update the keywords, However I get an

Mass Assignment Exception

Error

My current code is as follows, Am I doing anything in particular wrong?

// Save The Keywords...
$kwords = Input::get('keywords');

foreach($kwords as $key => $value)
{
    // Save The Keywords...
    Keywords::updateOrCreate( array('pack_id'=> $pack->pack_id, 'keyword_title' => $value));
}

Cheers


Solution

  • Laravel is going to complain if you try to mass-assign fields not specified in the model class definition.

    This is related to the fact that a malicious user could try to assign fileds in your model (i.e. adding some parameters to a form) that are not supposed to be updated from application's users

    In order to be able to mass assign the fields, you have to specify all the fields you'd like to be 'mass-assignable' in your model:

    class Keywords extends Eloquent {
    
        protected $fillable = array('pack_id', 'keyword_title');
    
    }
    

    Alternatively, you could make some field guarded (non mass-assignable) and all the other fields would be mass-assignable:

    class Keywords extends Eloquent {
    
        protected $guarded = array('guarded_field');
    
    }
    

    if you're using Laravel 4, check here for more info