简体   繁体   中英

Access collection in laravel 5.2

I'm using entrust for my roles and permissions on laravel 5.2 and I have this on my controller:

$user = Auth::user();
    $rol = $user->roles;
    dd($rol);

in my User model:

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

And get this: Snapshot

I'm tryng to acces and show "display_name" on my view and i can't, help! Thanks in advance.

As you have defined in your User model, a user could has many roles (which means a user has an array of roles), so you have to define of which role you want to display the display_name property. I you want to show the display_name property for all available roles for a user, this could be achieved with something like:

@foreach (Auth::user()->roles as $rol)
  $rol->display_name
@endforeach

I hope it helps to clear your doubts.

For see data in controller use $user = Auth::user()->with('roles')

use dd($rol->toArray()) for check data collection,

To get all the roles of user in comma separated then you can use implode() as:

$rol->implode('display_name', ', ');

then it gives you Admin, Manager

As I think Laravel's Entrust library has Many to Many Relationship between user and roles. So if you want to show the display name on your view you've to fetch items/objects from the collection you get from calling the method roles() You can do this as:

// Collection of Roles
$user_roles = $user->roles;
foreach($user_roles as $user_role) {
  echo $user_role->display_name;
}

Or if you want to fetch the first rle you can use

$user_roles->first()->display_name

I hope this helps you!

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