Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GKMelbo's avatar

Get all roles of a user

I've followed Jeffreys videos on ACL in "What's new in Laravel 5.1" and I've made a page where administrators can edit users. On the edit page of each user you can edit the general information about the user, but I also want to display the users roles and assign new roles to the user from the edit page. The problem is that I don't know how.
Here is my code:
User Model:

public function roles()
    {
      return $this->belongsToMany(Role::class);
    }

    public function assignRole($role)
    {
      return $this->roles()->save(
        Role::whereName($role)->firstOrFail()
      );
    }

    public function hasRole($role)
    {
      if (is_string($role)) {
        return $this->roles->contains('name', $role);
      }

      return !! $role->intersect($this->roles)->count();
    }

Role Model:

public function permissions()
    {
      return $this->belongsToMany(Permission::class);
    }

    public function givePermissionTo(Permission $permission)
    {
      return $this->permissions()->save($permission);
    }

UsersController:

public function editUser($id)
    {
      $user = User::find($id);

      return view('admins.editUser', compact('user'));
    }

EditUser.blade.php

<div class="panel panel-default">
    <div class="panel-heading">Roles</div>
        <div class="panel-body">
            
        </div>
</div>

Any suggestions how to achieve this?

0 likes
3 replies
zachleigh's avatar
Level 47

If you followed that video, your User model should have these methods:


    /**
     * User roles.
     *
     * @return BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    /**
     * Assign role to user.
     *
     * @param string $role
     *
     * @return Role
     */
    public function assignRole($role)
    {
        return $this->roles()->save(
            Role::whereName($role)->firstOrFail()
        );
    }

    /**
     * Return true if user has given role.
     *
     * @param string|Collection $role
     *
     * @return bool
     */
    public function hasRole($role)
    {
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }

        return !! $role->intersect($this->roles)->count();
    }

Assuming you have the relationship, this should give you a collection of the user's roles.

$user->roles;
GKMelbo's avatar

Wow, now I feel really stupid... $user->roles; was the missing part. Thanks for the help!

anand_aks's avatar

Can you point how we can get all the users with particular permission if the same code structure is used?

Please or to participate in this conversation.