4

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

Moppo
  • 18,797
  • 5
  • 65
  • 64
StuBlackett
  • 3,789
  • 15
  • 68
  • 113

2 Answers2

6

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

Moppo
  • 18,797
  • 5
  • 65
  • 64
  • Hi @Moppo this works on a Model without a relationship on it. However I have another model that has a relationship and it doesn't work. Any ideas? – StuBlackett Oct 12 '15 at 14:26
  • check [here](http://stackoverflow.com/questions/26829196/laravel-saving-mass-assignment-with-a-morphmany-relation) and see if it could be helpful, otherwise i suggest to post a new question with all the code details – Moppo Oct 12 '15 at 16:16
2

You need to define either $fillable or $guarded properties on your model. If you want everything except id to be fillable, here's how you can define this:

class Keywords extends Model {
    protected $guarded = array('id');
}
Okneloper
  • 1,247
  • 1
  • 14
  • 25