Laravel模型不存在属性检测

时间:2019-05-18 06:23:28

标签: laravel exception eloquent laravel-5.8

我有用户模型,其中包含以下字段:

id
name
email
password

为什么Laravel在请求不存在的属性时不返回错误。请求不存在的属性时如何返回错误?

代码:

$user = User::findOrFail(1);

echo $user->name; // This attribute exist in out table and we can continue...
echo $user->location; // Attribute `location` doesn't defined and we can't continue!!!

2 个答案:

答案 0 :(得分:0)

您可以覆盖模型getAttributeValue的方法,如下所示:

class User extends Authenticatable
{
    ...

    public function getAttributeValue($key)
    {
        $value = parent::getAttributeValue($key);
        if ($value) {
            return $value;
        }
        throw new \Exception("Attribute Does Not Exists!");
    }

   ...
}

答案 1 :(得分:0)

您可以在类似于以下代码的模型中覆盖__get方法:

public function __get($key)
{
    if (!array_key_exists($key, $this->attributes))
        throw new \Exception("{$key attribute does not defined !!! }", 1);

    return $this->getAttribute($key);
}