Модель Laravel не существует атрибута обнаружения - PullRequest
0 голосов
/ 18 мая 2019

У меня есть Пользователь модель с полями:

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 голосов
/ 18 мая 2019

Вы можете переопределить метод __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);
}
0 голосов
/ 18 мая 2019

Вы можете переопределить вашу модель getAttributeValue метод, как показано ниже:

class User extends Authenticatable
{
    ...

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

   ...
}
...