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

GeorgeW's avatar

Spatie roles and permissions relation column

Hello,

I am trying to add permissions to a non user model, this new model has primary key column which isn't id, if i change the column to id i am able to retrieve the permissions fine. Is there a way to tell roles and permissions to use a different column in the relation?

Thanks!

0 likes
4 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Yes, you can specify the foreign key column name in the belongsToMany method when defining the relationship between the model and the permissions. Here's an example assuming the model is named MyModel and the primary key column is named my_model_id:

use Spatie\Permission\Models\Permission;

class MyModel extends Model
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'my_model_permissions', 'my_model_id', 'permission_id');
    }
}

In this example, the third argument 'my_model_id' specifies the name of the foreign key column in the pivot table. Replace 'my_model_permissions' with the name of your pivot table and 'permission_id' with the name of the foreign key column for the permissions table if they are different.

1 like
GeorgeW's avatar

@snapey yea everything works fine with the model, just not the roles and permissions.

I have just overridden the permssions method as suggested by AI and its pulling through fine now.

Snapey's avatar

@GeorgeW so you have protected $primaryKey in your model?

overriding the spatie package, you may be forgoing its caching.

Please or to participate in this conversation.