Laravel 模型中的动态填充

Laravel Dynamic Fillable in Models

遇到了 laravel 5.2 的问题。

以下是 eloquent 创建操作(post 调用)期间的错误,

Model.php453 中的批量分配异常:column_name

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

  1. model中的Fillables通过以下代码动态填充:
    public function __construct() {
         $this->fillable(\Schema::getColumnListing($this->getTable()))
    }
    

目前调试到的方法如下:

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

  2. 在model.php行(450)中,

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

    上面的代码returns值为"false"并且$model::getFillableField()在数组列表中有column_name。

  3. 硬编码包含 table 列的 $fillable 变量消除了错误。 请帮助,我哪里出错了,解决方案是什么?

提前致谢。

试试这个。 将以下代码放入您的模型中,

public function __construct()
{
    $this->setFillable();
}
public function setFillable()
{
    $fields = \Schema::getColumnListing('table_name_here');

    $this->fillable[] = $fields;
}

这使得每一列都可以从 table 中填写。

您真正想做的是使 所有 字段可填写。

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

protected $guarded = [];

这在 5.2 中有效,即使在 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:

通过将 $guarded 设置为空数组,您正在创建一个空的黑名单,允许所有字段都可以批量分配。

此外,如果此模型曾经 将直接根据用户输入构建,请不要这样做。 Laravel 需要定义 $fillable$guarded 是有原因的。除非您的模型中的字段字面上是 1:1 且具有 public 形式,否则允许所有字段在批量分配时可写是一个安全漏洞。

创建一个使用数据库列的特征。

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Schema;

trait ColumnFillable
{
    public function getFillable()
    {
        return Schema::getColumnListing($this->getTable());
    }
}

现在在你的模型中使用这个特征。

<?php

namespace App;

use App\Traits\ColumnFillable;

class MyModel extends Model
{
    use ColumnFillable;

    ...

现在您再也不必手动指定 $fillable