Laravel Model 的 fillable (白名单)与 guarded (黑名单)

但是在新增前,需要先在模型类里设定好 fillable 或 guarded 属性,因为 Eloquent 默认会防止批量赋值

例如

protected $fillable = ['name'];
protected $guarded = ['price'];

定义了name 字段可以写入/修改,而 price 字段不可以。

需要注意的是,fillableguarded 只限制了 create 方法,而不会限制 save

我觉得Laravel这样设计的原因是,create 通常是使用 request中的所有请求参数来创建对象,而 save 则是一个字段一个字段的手动赋值,所以 create 有可能会恶意加入不应该插入的字段,例如 is_admin。基于此,create 还是需要有 fillable, guarded 来过滤一层比较安全。

猜你喜欢

转载自blog.csdn.net/qq_25615395/article/details/79923816