简体   繁体   中英

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

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 (ie 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

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM