问题
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?"
回答1:
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
回答2:
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()
来源:https://stackoverflow.com/questions/44070497/laravel-eloquent-return-only-one-value