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

tms1987's avatar

Eloquent question

I'm just working on the Role and abilities features as described in the Laravel from Scratch video: https://laracasts.com/series/laravel-6-from-scratch/episodes/54

Here, I want to add a list of users who have a role to my admin panel. (Later on I will add a function to remove that role). Therefore I need a collection of role-names as well as user-names. However, when I tried something like

$users->map->roles->flatten() 

I receive a collections of Roles, including the user_id of the user, but not ists user_name:

...
App\Models\Role {#4474
         id: 2,
         name: "moderator",
         label: "Moderator",
         created_at: "2021-02-13 16:30:26",
         updated_at: "2021-02-13 16:30:26",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4478
           user_id: 3,
           role_id: 2,
           created_at: "2021-02-13 16:30:26",
           updated_at: "2021-02-13 16:30:26",
         },
...

What do I need to do in eloquent to add the user name to the result?

0 likes
1 reply

Please or to participate in this conversation.