More elegant way to handle properties of null object

Posted 2 years ago by Indemnity83

Lets say I have a User model with a defined relationship for an avatar:

class User extends Model
{
    public function avatar()
     {
        return $this->hasOne(Avatar::class);
     }
}

Then somewhere (probably a veiw) I want to get the URL attribute for the users avatar; simple right? $user->avatar->url. The problem is when the user does not actually have an avatar, this doesn't fail gracefully, it throws a "Trying to get property of NULL" exception. So I end up having to write an accessor on the user model to check if its null:

public function getAvatarUrlAttribute() 
{
    $avatar = $this->avatar;
    return is_null($avatar) ? null : $avatar->url;
}

Now I can use $user->avatar_url in my view and everything is groovy; but it feels like there must be a better way?

Please sign in or create an account to participate in this conversation.