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

Randy_Johnson's avatar

DB wanted data not appearing through JOIN

I am using Spatie Permissions and Roles, I want to return the role name but it isn't appearing.

$data = DB::table('users')
            ->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
            ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
            ->select('users.*', 'model_has_roles.*', 'roles.*')
            ->get();
Illuminate\Support\Collection {#1393 ▼
  #items: array:1 [▼
    0 => {#1399 ▼
      +"id": 1
      +"name": "admin"
      +"email": "[email protected]"
      +"email_verified_at": null
      +"password": "5452352352352344DDASSFAGDGDAGDASGDGASDGASGASFFASDFAGH34TDAG"
      +"remember_token": null
      +"created_at": "2020-11-01 21:42:02"
      +"updated_at": "2020-11-01 21:42:02"
      +"role_id": 1
      +"model_type": "App\Models\User"
      +"model_id": 1
      +"guard_name": "web"
    }
  ]
}
0 likes
7 replies
Randy_Johnson's avatar

Yes, I think I understand, because of the linking of the data through migration, I am able to do this. Correct?

automica's avatar

@randy_johnson I think you’d benefit in reading the docs for that spatie package. You can do this much simpler using the eloquent relationships that are set up in the package

Randy_Johnson's avatar

How do I get the role name is blade.

                            <td>{{$datum->name}}</td>
                            <td>{{$datum->email}}</td>
                            <td>{{$datum->roles['name']}}</td>   <--------????
                            <td>{{$datum->updated_at}}</td>
MichalOravec's avatar
Level 75

$user->roles is a collection so what do you think?

You need use foreach or

{{ $user->roles->pluck('name')->implode(' ') }}
Randy_Johnson's avatar

I am using a foreach

@foreach($data as $datum)
                        <tr>
                            <td>{{$datum->name}}</td>
                            <td>{{$datum->email}}</td>
                            <td>{{$datum->roles['name']}}</td>
                            <td>{{$datum->updated_at}}</td>
                            <td>
automica's avatar

@randy_johnson its much clearer if your variable is named based on whats in it.

$data = DB::table('users')

is best as

$users = DB::table('users')

In your blade you would then do:

@foreach($users as $user)
                        <tr>
                            <td>{{ $user->name }}</td>
                            <td>{{ $user->email }}</td>
                            <td>{{ $user->roles->pluck('name')->implode(' ') }}</td>
                            <td>{{ $user->updated_at }}</td>
                         </tr>
@endforeach

its much clearer reading the code what object you are displaying.

so

$user->name

is more obvious than

$datum->name

Please or to participate in this conversation.