模型中的Laravel动态填充

模型中的Laravel动态填充

本文介绍了模型中的Laravel动态填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在laravel 5.2中遇到了问题.

Got stuck in a issue with laravel 5.2.

以下是雄辩的创建操作(调用后)中的错误,

Following is the error during eloquent create operation(post call),

Model.php 453中的质量分配异常:column_name

Mass Assignment Exception in Model.php 453: column_name

以下是要考虑的先决条件:

Following are the prerequisites, which are to be taken into consideration:

  1. 模型中的可填写内容通过以下代码动态填充:
  1. 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:

  1. 在插入之前,在控制器中的$ model :: getillableField()中会给出适当的可填充数组.

  1. Before insertion, in controller, $model::getillableField(), gives proper fillable array.

在model.php第450行中,

In model.php line(450),


if ($this->isFillable($key)) {
      $this->setAttribute($key, $value);
}

上面的代码返回值为"false",并且$ model :: getFillableField()在数组列表中具有column_name.

the above code returns the value as "false" and $model::getFillableField() has the column_name in the array list.

使用表的列对$ fillable变量进行硬编码可消除该错误.请帮忙,我哪里出问题了,解决方案是什么?

Hardcoding $fillable variable with columns of table removes the error.Please Help, where i am going wrong and what is the solution for it?

谢谢.

推荐答案

您真正想做的是使 ALL 字段可填充.

What you are really trying to do is make ALL fields fillable.

在Laravel中执行此操作的正确方法是:

The correct way to do this in Laravel is this:

protected $guarded = [];

即使在5.3中找到了它的文档,它也可以在5.2中使用.

This works in 5.2, even though the documentation for it is found in 5.3.

(相关源代码对于5.2 )

( 5.3版本的文档):

通过将$guarded设置为一个空数组,您将创建一个空的黑名单,从而允许对所有字段进行批量分配.

By setting $guarded to an empty array, you are creating an empty black list, allowing all fields to be mass assignable.

此外,如果此模型是 ever ,将直接根据用户输入进行构建,请不要这样做.由于某种原因,Laravel需要定义$fillable$guarded.除非您的模型具有从字面上看是采用公共形式的1:1的字段,否则在批量分配时允许所有字段都可写是一个安全漏洞.

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动态填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 16:50