Laravel - Eloquent return only one value

2019-07-28 15:24发布

How can I return one value from a belongsToMany relation.

This is my relation:

public function role() {

    return $this->belongsToMany('App\Role');

}

Now when I want to access the Role Name I have to do the folowing:

Auth::user()->role[0]->name 

But I just want to do

Auth::user()->role

But now my question is: "How can I do that?"

2条回答
ら.Afraid
2楼-- · 2019-07-28 15:46

to do this you need add custom attribute to user model as the following:

User Model:

protected $appends = ['role'];  // add new attribute to user model

public function getRoleAttribute()
{
   return $this->roles->first(); // don't use roles() it would execute every time  
}

public function roles() {
return $this->belongsToMany('App\Role');
}

now you can use

Auth::user()->role
查看更多
聊天终结者
3楼-- · 2019-07-28 15:54
Auth::user()->role()->first()

Besides the question itself, i suggest you to use the plural name for belogsToMany relations: it is a common best practice and makes the code much more expressive.

public function roles() {
    return $this->belongsToMany('App\Role');
}

Auth::user()->roles()->first()
查看更多
登录 后发表回答