DEV Community

Muhamad Jamil
Muhamad Jamil

Posted on

Eager load for getting role name in spatie/permissions

at first im using this method to show role name in blade view

        <td>
        @if(!empty($user->getRoleNames()))
            @foreach($user->getRoleNames() as $role)
                <label class="badge bg-primary">{{ $role }}</label>
            @endforeach
        @endif
        </td>
Enter fullscreen mode Exit fullscreen mode

but when i see in clockwork, there are many query from role, yes its a n+1 problem

so i use eager load for this

in UserController i added this
$data = User::with(['roles']);

so when i query User table, roles table will join it

and in blade view i added this

@if(!empty($user->roles))
            @foreach($user->roles as $role)
                <label class="badge bg-primary">{{ $role->name }}</label>
            @endforeach
        @endif
Enter fullscreen mode Exit fullscreen mode

if you have another way, feel free to discuss

Discussion (0)