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

oriceon's avatar

Roles & Permissions

Hello. I have a custom roles and permissions for laravel 5 but need to change way he works.

I have

permissions__lists
    id, name

permissions__roles
    id, role_id, permission_name

users__roles
    id, name

in Role model i have

    public function permissions()
    {
            return $this->belongsToMany('App\Permission', 'permissions__roles', 'role_id', 'permission_name');
    }

but this return:

select
    `permissions__lists`.*,
    `permissions__roles`.`role_id` as `pivot_role_id`,
    `permissions__roles`.`permission_name` as `pivot_permission_name`
from `permissions__lists`
inner join `permissions__roles` on `permissions__lists`.`id` = `permissions__roles`.`permission_name`
where `permissions__roles`.`role_id` = 1

How can i make belongsToMany to inner join by permissions__lists.name not by permissions__lists.id ?!

Edit: Is other and nice way than remove id from permissions__lists and make name as primary then in Permission model to add protected $primaryKey = 'name';

That seems to work..

0 likes
2 replies
bobbybouwmann's avatar
Level 88

You can do something like this

class Role extends Model {

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'permission_role', 'role_id', 'permission_name');
    }

}
class Permission extends Model {

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'permission_role', 'permission_name', 'role_id');
    }

    public function getKeyName()
    {
        if (empty($this->relations)) {
            return 'name';
        }

        return 'id';
    }

}
1 like

Please or to participate in this conversation.