Home > other >  How to get all the roles for all the users in laravel?
How to get all the roles for all the users in laravel?

Time:07-23

I'm using a function to get all roles for all users in laravel.

I'm getting the following json object:

{
  "users": [
      {
     id: 1,
     name: "abc",
     user_roles: [
         {
             "id": 1,
             "role_id": 1,
             "user_id": 1,
         },
         {
             "id": 1,
             "role_id": 2,
             "user_id": 1,
         },
       ]
      ]
     }
}

I want to get the specific roles in the "user_roles" part, for example:

{
  "users": [
      {
     id: 1,
     name: "abc",
     user_roles: [
         {
             "id": 1,
             "role": "role1",
         },
         {
             "id": 1,
             "role": "role2",
         },
       ]
      ]
     }
}

I have 3 tables: users, roles, and user_role.

The issue is because I'm extracting elements from "user_role", what can I add to get the above result?

CodePudding user response:

In user_role table you have to define belongsTo relationship like below

public function role_name(): BelongsTo
{
   return $this->belongsTo(Role::class,'role_id','id');
}

then use with() inside user_roles like below

User::with(['user_roles' => function($query){
         $query->with('role_name');
      }])
      ->get();

so, output will be

[id] => 1
[name] => abc
[user_roles] => Array
    (
        [0] => Array
            (
                [id] => 1
                [a_role_id] => 1
                [a_user_id] => 1
                [role_name] => Array
                    (
                      [id] => 1
                      [name] => role1
                    )
            )

        [1] => Array
            (
                [id] => 1
                [a_role_id] => 2
                [a_user_id] => 1
                [role_name] => Array
                    (
                      [id] => 2
                      [name] => role2
                    )
            )
     )

CodePudding user response:

You can use laratrust or larapermission pakage, to avoid any problem.

CodePudding user response:

Have you checked Laravel Docs?

To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names and contains user_id and role_id columns. This table is used as an intermediate table linking the users and roles.

You can find complete information at Laravel Eloquent Many to Many Relationship

  • Related