Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 907
StuBlackett Avatar asked Feb 09 '23 20:02

StuBlackett


2 Answers

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

like image 189
Moppo Avatar answered Feb 11 '23 17:02

Moppo


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');
}
like image 24
Okneloper Avatar answered Feb 11 '23 18:02

Okneloper