Laravel print role of user in table -
i have laravel application. i'm using this package roles , permissions. works great.
i display table of users roles. i'm solving through definition of following in userscontroller.
public function listusers() { $users_admin = role::where('name', 'admin')->first()->users()->get(); $users_buyers = role::where('name', 'buyer')->first()->users()->get(); $users_sellers = role::where('name', 'seller')->first()->users()->get(); return view('admin.users.index', [ 'users_admin' => $users_admin, 'users_buyers' => $users_buyers, 'users_sellers' => $users_sellers ]); }
in view, have 3 separate loops display 3 tables (for admin users, buyers , sellers).
needless don't approach , ideally have single table displaying users role.
so idea can write following code (or similar) in userscontroller:
$users = user::all();
while view contains single foreach stating following:
@foreach( $users_sellers $user ) <tr> <td align="center" class="hidden-xs">{{ $user->id }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->displayrole($user->id) }}</td> </tr> @endforeach
in above pseudocode, have defined helper retrieves role based on user-id. problem can't figure out put in helper function?
note: if there other (better) methods helper, work me.
as far see package adds relation in user model, $user->roles
should collection roles assigned current user. not make query each user should eager load users roles, this: $users = user::with('roles')->get();
.
Comments
Post a Comment