Eloquent ORM:定义允许的模型属性

cwe*_*ske 6 laravel eloquent

在laravel 雄辩的 ORM中,有没有办法定义模型的允许属性?

默认情况下,我可以将任何属性放入模型的构造函数中 - 但是当我实际尝试将模型保存到数据库时,我只会收到有关错误属性名称的通知.

示例代码:

// this works although there is a typo in "lastname"
$user = new \App\User(['firstname' => 'foo', 'lastnam' => 'bar']);

// this errors out with an SQL error
$user->save();
Run Code Online (Sandbox Code Playgroud)

那么,有没有办法让Laravel自动检查请求的输入数据中是否存在无效密钥?

Pau*_*aul 7

如果您不仅要防止使用fill()方法填充不允许的属性,还要防止直接设置它们,例如$model->foo = 'bar',那么您必须覆盖Model::setAttribute()方法。

最好在扩展 Eloquent 的自定义基础模型中进行。所以在app/Model.php

namespace App;

use Exception;
use Illuminate\Database\Eloquent\Model as Eloquent;

class Model extends Eloquent
{
    // this should be actually defined in each sub-model
    protected $allowed = ['firstname', 'lastname'];

    public function setAttribute($key, $value)
    {
        // this way we can allow some attributes by default
        $allowed = array_merge($this->allowed, ['id']);

        if (! in_array($key, $allowed)) {
            throw new Exception("Not allowed attribute '$key'.");
        }

        return parent::setAttribute($key, $value);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在不应允许无效属性的模型中,您可以扩展此基本模型:

use App\Model;

class User extends Model
Run Code Online (Sandbox Code Playgroud)


Tom*_*ler 5

我不相信这可以在本地完成.我认为Laravel在这个意义上是故意宽容的,如果我在某处设置属性时出错,我个人不介意有SQL错误而不是Eloquent错误.

话虽这么说,当设置不存在的属性时,自定义模型失败并不困难:

// User.php

protected $fillable = [
    'firstname',
    'lastname',
];

public function fill(array $attributes)
{
    foreach ($attributes as $key => $value) {
        if (!in_array($key, $this->getFillable())) {
            throw new \Exception("Attribute [{$key}] is not fillable.");
        }
    }

    return parent::fill($attributes);
}
Run Code Online (Sandbox Code Playgroud)