DEV Community

Muhamad Jamil
Muhamad Jamil

Posted on

3 2

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more