简体   繁体   中英

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

Testgrammatical或拼写错误►澄清意义而不改变它►正确的小错误►添加相关资源或链接►始终尊重原作者

Get the data using eager loading :

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

Then display the data:

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

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

I guess relation here is many to many, so you need to change roles() relation to belongsToMany()

If you're using some package with many to many relationship, but you're only attach one role for user, you can display role name with this:

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

Also, you could use accessor to get full name:

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

To display full name using accessor:

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

@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM