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

repulsor's avatar

Laravel Relations

Trying hard to figure this out.

I have 3 tables.

1.Users (id,name) 2.Roles (id,role_id,role) 3.User_roles (id,user_id,role_id)

User may or may not have more than one role.

Which all relations should I be using?

What I want as a result is this

id,Name,role_id,role (+ other fields) These 4 are the required ones.

I have gone through the docs, but it seems too confusing. Please point me in the right direction. I would really appreciate few lines of how to do instead of direct linking. Thanks a ton. Any help is highly appreciated

0 likes
5 replies
manelgavalda's avatar

If the user can only have 1 role I don't think you need the user_roles table.

You can simply add a role_id column in your users table.

aurawindsurfing's avatar

Hi @repulsor

Your tables should look like this:

users
* user_id
* name

roles
* role_id
* name

role_user
* user_id
* role_id

Now what is important here is to have the pivot table naming correct, it needs to be alphabetical order of tables that it connects and singular so role_user not role_users or user_roles etc.

Then on your User model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Just like in the docs. and the reverse on your Role model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

The in your code you can use it like this:

$roles = App\User::find(1)->roles()->orderBy('name')->get();

The docs are really good, you just have to read them carefully. Also watch this series:

https://laracasts.com/series/eloquent-relationships/episodes/3

Hope it helps!

repulsor's avatar

@AURAWINDSURFING - I get an empty array doing what you suggested. Here is my schema.

Users:
id
name

Roles:
id
role_id
role

role_user:
id
user_id
role_id

Added this in user.php

public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

And calling this from controller gives me empty array.

$response = User::find(1)->roles;

Any idea why?

Snapey's avatar

Actually

users

  • id
  • name

roles

  • id
  • name

role_user

  • user_id
  • role_id

And then Laravel does its magic

Then

$response = User::find(1)->roles()->get();

or

$response = User::with ('roles')->find(1);

Then response will be user object with nested roles

1 like

Please or to participate in this conversation.