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

baeckerman83's avatar

Three tables connected - How to do with hasMany?

Hi! Can someone show me how I can handel a database table model where I have three tables.

  1. User with user id (Laravel Table)
  2. Rights with rights id (my own Table)
  3. UserRights Table with rights und user id (my own table)

Because one User can have many rights, also one right can have many users. How can I get the rights name for an User?

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

Please read about many to many relationships, it explains what you're asking: https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

Also pay attention to how the tables are named. Your "UserRights" table should be 'right_user'. If you don't follow eloquent naming conventions, you will have more trouble and have to use more code to make things work. https://laravel.com/docs/5.7/eloquent#eloquent-model-conventions

users
--------
-id
-other fields

rights
--------
-id
-name (or something)
-other fields

right_user
---------------
-user_id
-right_id

Then in User model

public function rights() {
    return $this->belongsToMany(App\Right::class);
}

and in Right model

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

Then use something like

$users = User::with('rights')->get();

foreach ($users as $user) {
    foreach ($user->rights as $right) {
        echo $right->name;
    }
}
baeckerman83's avatar

I tried this, but it's not working. I had to use return $this->belongsToMany('App\Right'); instead of App\Right::class.

Please or to participate in this conversation.