模型中的 Laravel 动态可填充
遇到了 Laravel 5.2 的问题.
以下是eloquent create操作(post call)时的错误,
Model.php 453 中的批量赋值异常:column_name
以下是需要考虑的先决条件:
- 模型中的可填充物由以下代码以动态方式填充:<前>公共函数 __construct() {$this->fillable(Schema::getColumnListing($this->getTable()))}
目前调试的方法如下:
在插入之前,在控制器中,$model::getillableField() 给出了适当的可填充数组.
在 model.php 行(450)中,
<前>如果 ($this->isFillable($key)) {$this->setAttribute($key, $value);}上面的代码返回值为false",$model::getFillableField() 在数组列表中有 column_name.
使用表列对 $fillable 变量进行硬编码可消除错误.请帮助,我哪里出错了,解决方法是什么?
提前致谢.
解决方案您真正想做的是使所有字段可填写.
在 Laravel 中执行此操作的正确方法是:
protected $guarded = [];
这在 5.2 中有效,即使它的文档在 5.3 中找到.
(相关源码对于 5.2)
(来自 5.3 的文档):
<块引用>如果你想让所有的属性都可以批量赋值,你可以将 $guarded 属性定义为一个空数组:
通过将 $guarded
设置为一个空数组,您正在创建一个空的黑名单,允许所有字段都可以批量分配.
此外,如果此模型永远将直接根据用户输入构建,请不要这样做.Laravel 要求定义 $fillable
或 $guarded
是有原因的.除非您的模型具有与公共表单 1:1 的字段,否则允许所有字段在批量分配时可写是一个安全漏洞.
Got stuck in a issue with laravel 5.2.
Following is the error during eloquent create operation(post call),
Mass Assignment Exception in Model.php 453: column_name
Following are the prerequisites, which are to be taken into consideration:
- Fillables in model are filled in a dynamic manner by the following code:
public function __construct() { $this->fillable(Schema::getColumnListing($this->getTable())) }
Following are the methods which are debugged till now:
Before insertion, in controller, $model::getillableField(), gives proper fillable array.
In model.php line(450),
if ($this->isFillable($key)) { $this->setAttribute($key, $value); }
the above code returns the value as "false" and $model::getFillableField() has the column_name in the array list.
Hardcoding $fillable variable with columns of table removes the error. Please Help, where i am going wrong and what is the solution for it?
Thanks in advance.
解决方案What you are really trying to do is make ALL fields fillable.
The correct way to do this in Laravel is this:
protected $guarded = [];
This works in 5.2, even though the documentation for it is found in 5.3.
(relevant source code for 5.2)
(Documentation from 5.3):
If you would like to make all attributes mass assignable, you may define the $guarded property as an empty array:
By setting $guarded
to an empty array, you are creating an empty black list, allowing all fields to be mass assignable.
Also, if this model is ever going to be constructed directly from user input, please do not do this. Laravel requires either $fillable
or $guarded
to be defined for a reason. Unless your model has fields that are literally 1:1 with a public form, then allowing all fields to be writable on mass assignment is a security vulnerability.
相关文章