如何保护Laravel模型属性

时间:2017-09-23 06:12:06

标签: laravel eloquent

使用其他框架或纯PHP时,我保护我的模型属性。然后,我根据需要创建公共getter和setter,并使用__get()__set()代理它们。这有助于我晚上睡觉。

最近我开始使用Laravel,我很惊讶Eloquent模型的'未受保护'。我了解我可以使用$guarded$fillable属性来控制质量分配,但这仍然为意外访问留下了很大的空间。

例如,我的模型具有status属性。它具有在模型创建时设置的默认值,并且只应在调用$model->activate()$model->deactivate()时进行修改。但默认情况下,Laravel允许开发人员直接修改它。据我所知,防止这种情况的唯一方法是创建一个setter,并在调用它时抛出异常。

我错过了什么吗?也许我只需要放松一下?构建默认安全的Eloquent模型的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

您可以覆盖__get和__set方法。您需要定义一个数组protectedProperties和一个布尔变量protectedChecks,以便您可以控制模型字段。

protected $protectedChecks = true;

protected $protectedProperties = [ 'status' ];

protected $fillable = ['status'];

public function __get($key)
{
    return (in_array($key, $this->fillable) && !in_array($key, $this->protectedProperties)) ? $this->attributes[$key] : null;
}

public function __set($key, $value)
{
    if(!$this->protectedChecks || !in_array($key, $this->protectedProperties))
            return parent::__set($key, $value);
        trigger_error('Protected Field');
}

public function activate()
{
    $this->protectedChecks = false;
    $this->status = 1;
    $this->save(); // this is optional if you want to save the model immediately
    $this->protectedChecks = true;
}

如果你想使用每个模型,你应该在BaseModel中写上面的内容。

答案 1 :(得分:0)

您可以尝试:

<?php

class User extends Eloquent {

     protected $hidden = array('password', 'token');

}

答案 2 :(得分:0)

我所看到的可能来自symfony或其他使用Mapping作为基础来处理数据库层的系统。忘记你在那里所做的事情,因为Eloquent使用Active Records,这是不同的。 最好的方法是:Eloquent: Accessors & Mutators Alo检查laracast有解释如何使用绝对属性以旧的PHP时尚方式。