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

Masamah's avatar

Eager Loading in joinning roles and permissions in Laravel

Halo folks! am wondering if i can change the following code to have eager-loading because is taking a lot of RAM size...

static public function retrievePermissions($slug, $role_id) { return self::select('permissions_roles.id') ->join('permissions', 'permissions.id', '=', 'permissions_roles.permission_id') ->where('permissions_roles.role_id', '=', $role_id) ->where('permissions.slug', '=', $slug)->count();

}
1 like
5 replies
tisuchi's avatar

@masamah How about this?

static public function retrievePermissions($slug, $role_id)
{
    return Role::with('permissions')
        ->where('id', $role_id)
        ->whereHas('permissions', function ($query) use ($slug) {
            $query->where('slug', $slug);
        })
        ->count();
}

I assume Role has many Permission relationships via a pivot table permissions_roles.

2 likes
Masamah's avatar

@tisuchi Thank you for enlightening response but i get an error because i have policies that i run though that code. the following is the error...

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'permissions.role_id' in 'where clause' (Connection: mysql, SQL: select count(*) as aggregate from roles where id = 4 and exists (select * from permissions where roles.id = permissions.role_id and slug = Schools))

1 like
Masamah's avatar

Maybe we need a space where i can share the code properly

1 like
tisuchi's avatar

@Masamah

I assume Role has many Permission relationships via a pivot table permissions_roles.

Do you have a proper relationship?

2 likes
Masamah's avatar

@tisuchi yes! Roles and Permissions tables. PermissionRole table is for having role_id and permission_id. Can i show it you via github or email?

1 like

Please or to participate in this conversation.