如果Laravel 5.4中的对象为空,则返回字符串

时间:2017-07-18 13:32:43

标签: laravel eloquent

这是我的用户模型:

/**
 * The settings that belong to the user.
 */
public function settings()
{
    return $this->hasMany(Setting_user::class); 
}

/**
* Get user's avatar.
*/
public function avatar()
{
   $avatar = $this->settings()->where('id',1);

    if(count($this->settings()->where('id',1)) == 0 )
    {
        return "default-avatar.jpg"; 
    }

    return $this->settings()->where('id',1);
}

在我看来,我正在访问这样的值:

Auth::user()->avatar

当用户拥有头像时,一切都很好。但是当为空时方法avatar()返回一个字符串,我得到以下错误:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: C:\xampp\htdocs\laravel\laravel-paper-dashboard\resources\views\dashboard\user-profile.blade.php)

1 个答案:

答案 0 :(得分:2)

您可能希望改为使用Eloquent Accessor

public function getAvatarAttribute() {
    $avatar = $this->settings()->where('id',1)->first(); // Changed this to return the first record

    if(! $avatar)
    {
        return "default-avatar.jpg"; 
    }

    // You will need to change this to the correct name of the field in the Setting_user model.
    return $avatar->the_correct_key; 
}

这样您就可以在模板中调用Auth::user()->avatar

否则Eloquent认为你正试图建立关系。