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

kaizokupuffball's avatar

Laravel relationship issue.

I have three tables "users", "roles" and "role_users". The user table does not have any role_id field. So mapping of user with role is maintained in "role_users" table by having role_id and user_id fields.

Here is what i am currently doing in User model:

public function teachers() {
    return $this->has_many('Role')->where('name','teacher');
}

This is not working, but i could not understand that how would i make the relationship in this model.

0 likes
4 replies
ismaile's avatar
ismaile
Best Answer
Level 30

You should use a belongsToMany in this case:

public function teachers() {
    return $this->belongsToMany('App\Role')->wherePivot('name','teacher');
}

Besides, your pivot table should be called role_user instead of role_users, that's the Laravel convention: here you can find more details about it https://laravel.com/docs/6.x/eloquent-relationships#many-to-many This pivot table should have a user_id, a role_id, and a name attribute.

1 like

Please or to participate in this conversation.