LARAVEL 5.3,获取用户名和角色名(使用Laravel模型关系)

LARAVEL 5.3, Get User Name and Role Name (Using Laravel Model Relationships)

测试语法或拼写错误 ► 澄清意思而不改变它 ► 纠正小错误 ► 添加相关资源或链接 ► 永远尊重原作者

获取数据使用eager loading:

$user = User::where('id', $userId)->with('roles')->first();

然后显示数据:

{{-- Display full name --}}
{{ $user->first_name.' '.$user->last_name }}

{{-- Display all role names of the user --}}
@foreach ($user->roles as $role)
    {{ $role->name }}
@endforeach

我想这里的关系是多对多的,所以你需要将 roles() 关系更改为 belongsToMany()

如果您正在使用一些具有多对多关系的包,但您只为用户附加一个角色,您可以这样显示角色名称:

{{ $user->roles->first()->name }}

此外,您可以使用 accessor 获取全名:

public function getFullNameAttribute($value)
{
    return $this->first_name.' '.$this->last_name;
}

要使用访问器显示全名:

{{ $user->full_name }}
@foreach($users as $user)
{{$user->name}}  {{$user->roles->first()->name}}

@endforeach