2017-07-18 55 views
0

空这是我的用户模型:返回字符串,如果对象是在Laravel 5.4

/** 
* 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); 
} 

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

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

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) 

回答

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认为你试图建立关系。

+0

嗨乔希,这是我最初做的,但我有同样的错误。 – Marco

+0

您是否从用户模型中删除/替换原始的“avatar()”方法? – Josh

+1

它现在工作谢谢! – Marco

相关问题