How to show role name in the users list?



  • Hello,

    I want modify the users list to add the role name.
    I modify the controller like this :

    public function index()
    {
        $users = $this->user->with('roles')->get();
    
        $currentUser = $this->auth->user();
    
        return view('user::admin.users.index', compact('users', 'currentUser'));
    }
    

    But I got an error :
    Call to undefined method Modules\User\Repositories\Sentinel\SentinelUserRepository::with()

    Someone would have any idea ?

    Thanks.


  • Global Moderator

    Hey, @anardil06

    Users object already have access to that information you don't need to explicitly retrieve that.

    In your view

    @foreach($users as $user)
        {{ $user->name }}
        @foreach ($user->roles as $role)
            {{ $role->name }}
        @endforeach
    @endforeach
    


  • Hello,

    Thanks for your answer.
    In fact I'm building an API controller for the module User and I want to get the list of users with roles in JSON format to use it in VueJs.
    If I do only => $users = $user->all(); I don't have the roles.

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(UserRepository $user)
    {
        $users = $user->all();
        return response()->json($users);
    
    }
    

    I looked in the documentation of Sentinel and I didn't find the solution.
    Do you have any idea?

    Thank you.



  • Ok I found. I'm new with Laravel so I'm not familiar with some notions.

    I modified the class "SentinelUserRepository" in "Modules\User\Repositories\Sentinel" and I added a new method.

    /**
     * Returns all the users with roles
     * @return object
     */
    public function allWithRoles()
    {
        return $this->user->with('roles')->get();
    }
    

    Then in the API Controller, now I call the new method:

    public function index(UserRepository $user)
    {
        $users = $user->allWithRoles();
        return response()->json($users);
    
    }
    

    If you have a better idea...


Log in to reply
 

Looks like your connection to AsgardCms was lost, please wait while we try to reconnect.