$users = User::with('roles')->all();
Jan 24, 2016
10
Level 2
How can I put all roles in users list?
How can I put all roles in users list in user controller? I am using angularjs to call api.
here is my code but not work.
class UsersController extends Controller
{
public function index()
{
$users = User::all->roles;
return $users;
}
}
e.g. UserName roles A Manger, Member B Member
Level 29
You can trim it down a bit
public function edit($id)
{
$user = User::findOrFail($id);
$roles = array();
foreach(Role::all() as $role) {
$roleArr = [
'id' => $role->id,
'name' => $role->name,
'display_name' =>$role->display_name,
'description' => $role->description,
'created_at' => $role->created_at
'updated_at' => $role->updated_at
];
// you could also simply use
// $roleArr = $role->toArray() if displaying all non-hidden fields
if($user->roles->contains('id',$role->id)) { // $user->roles will be a collection which has many useful methods
$roleArr['selected'] = true;
}
$roles[] = $roleArr;
}
return Response::json(array_merge($user->toArray(),['roles'=>$roles]));
}
1 like
Please or to participate in this conversation.