我有用户模型,其中包含以下字段:
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!!!
答案 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);
}