Reputation: 5004
I have User model with fields:
id
name
email
password
Why the Laravel does not return an error during the request for a non-existent attribute. How to return an error when a non-existent attribute is requested?
Code:
$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!!!
Upvotes: 3
Views: 3015
Reputation: 487
you can override __get method in model like below code :
public function __get($key)
{
if (!array_key_exists($key, $this->attributes))
throw new \Exception("{$key attribute does not defined !!! }", 1);
return $this->getAttribute($key);
}
Upvotes: 1
Reputation: 521
You can override your model getAttributeValue
method like below:
class User extends Authenticatable
{
...
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
if ($value) {
return $value;
}
throw new \Exception("Attribute Does Not Exists!");
}
...
}
Upvotes: 3