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

错误是: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).

任何帮助都将不胜感激.

推荐答案

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

如果你愿意,你也可以使用create的方法.它会创建一个新模型并直接保存:

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

Laravel相关问答推荐

在Vite list 中找不到文件:Resources/scss/hrms.scss.如何使用LARAVEL VITE解决这个问题?

在 blade laravel 中以格式编号显示长数字

Laravel 9 上的数组差异助手

RuntimeException 未安装 Zip PHP 扩展

laravel render() 方法有什么用?

为什么 Laravel 5 会自动更新我的日期字段?

安卓 retrofit |发布自定义对象(将 json 发送到服务器)

Laravel:Blade foreach 循环 bootstrap 列

SQLSTATE [HY000]:一般错误:1005 无法创建表 - Laravel 4

在 laravel 5.2 中禁用特定路由的 Web 中间件

带有时间戳的 Laravel 5.1 eloquent::attach() 方法

Cookie::forget 不工作 laravel 5.1

如何从 laravel 中的现有数据库创建迁移

如何将Carbon 转换为字符串,只取日期?

Laravel 字符串验证以允许空字符串

Laravel 4:将什么作为参数传递给 Url 类?

如何在 Laravel 中使用补丁请求?

如何在laravel中 for each 用户生成唯一的随机值并将其添加到数据库中

Laravel 部署……有标准的方式吗?

如何在不要求用户登录 Laravel 的情况下验证Electron邮件