問題描述
遇到了 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.
這篇關于模型中的 Laravel 動態可填充的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!