Laravel - Mass Assignment Exception error

五迷三道 提交于 2019-12-20 17:42:09

问题


I am trying to save multiple rows to a table, however, I am presented with a Mass Assignment Error.

The error is: Illuminate \ Database \ Eloquent \ MassAssignmentException criteria_id

$criteria->save();

    $criteria_id = $criteria->id;

     foreach(Input::get('bedrooms') as $bedroom){
        $new_bedroom=array(
            'criteria_id' => $criteria->id,
            'bedroom' => $bedroom,
            );
        $bedroom = new Bedroom($new_bedroom);
        $bedroom->save();
    }

My database structure is:

so there isn't any incorrect spelling. The criteria_id comes from the variable from the recently saved criteria (see code above forloop).

Any help would be greatly appreciated.


回答1:


To be able to set properties by passing them to the model's constructor, you need to list all the properties you need in the $fillable array. As mentioned in the Docs

class Bedroom extends Eloquent {
    protected $fillable = array('criteria_id', 'bedroom');
}

Also you can use the create method if you want. It creates a new model and saves it directly:

foreach(Input::get('bedrooms') as $bedroom){
    $new_bedroom=array(
        'criteria_id' => $criteria->id,
        'bedroom' => $bedroom,
        );
    $bedroom = Bedroom::create($new_bedroom);
}



回答2:


The inverse of what lukas said is "guarded". Instead of "white-listing" fields, you could just declare which are guarded.

For example:

class Bedroom extends Model
{
    protected $guarded = ['id'];
}

This was more useful for me because I didn't really care about most fields.

Gotten from the docs for Laravel 5.2 but I assume it works on older versions.

To allow any fields, you could just provide an empty array:

class Bedroom extends Model
{
    protected $guarded = [];
}


来源:https://stackoverflow.com/questions/26724117/laravel-mass-assignment-exception-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!