Laravel - Eloquent return only one value

淺唱寂寞╮ 提交于 2020-01-05 08:18:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!