Laravel MassAssignmentException 来自firstOrNew by id

标签 laravel laravel-5 mass-assignment

我尝试使用 Laravel 的 firstOrNew 方法保存数据,该方法会产生 MassAssignmentException 错误。

我不明白为什么 firstOrNew 方法应该触发批量分配异常,因为它只是查看数据库,而不是尝试保存任何内容。来自 the docs :

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database.

为什么我的代码会抛出 MAE:

$tour = Tour::firstOrNew(array('id' => $this->request['id']));

据我了解,上面的代码所说的基本上都是“查看数据库中是否有具有该 ID 的行,如果有,则返回该行,如果没有,则创建一个具有相关 ID 的新对象”特性”。它没有保存任何数据,那么问题是什么?

请注意,仅当该行不存在时才会发生错误。

最佳答案

firstOrNew()使用newInstance()它使用构造函数创建新模型。 Constructor uses fill()方法就是批量分配。这就是为什么你会遇到异常(exception)。

因此,您需要设置 $fillable 数组才能使用 firstOrNew()

关于Laravel MassAssignmentException 来自firstOrNew by id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888273/

相关文章:

laravel - Eloquent 查询获取所有浏览次数超过 0 的帖子,但不排除过去 24 小时内创建的帖子?

php - Laravel 按自定义日期字段排序

laravel-5 - Laravel5 对模型的依赖注入(inject)

php - laravel队列:work out of memory

ruby-on-rails - ActiveAdmin:无法批量分配 protected 属性:电子邮件、密码、password_confirmation

ruby-on-rails - mass_assignment_authorizer 的更改导致 Ruby on Rails 3.1 中的错误

php - Eloquent 嵌套关系与一些约束

php - 使用 Laravel - Php 将输入值传递给 URL

html - Angular 2双向绑定(bind)从html输入标签中删除name属性

ruby-on-rails - 升级到 Rails 4 - 强大的参数