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

PaulCatalin97's avatar

getting id from the 3th table

i will explain what i have in the first section and then what i want to get.

I have those 3 tables:

first: users

protected $fillable = [
        'name', 'email', 'password',
    ];

the pivot table: user_to_role

protected $fillable = [
        'id', 'user_id', 'role_id'
    ];

and the third one: roles

protected $fillable = [
        'id', 'role_name', 
    ];

role_name is admin and client

When I login/register I want to show the view for the specific role of the user

but I don't really know how to do that in the controller, I have something like this but I know it's not good

public function index()
    {
        if(Auth::user()->role_id==1){
				and something here wich i dont know
            return view('homeadmin');
        }

    }

I know i have to take the role id from the 3th table, make the connection with the pivot and then with the user but i dont really know how

0 likes
3 replies
gzai's avatar

set your relationship in users, user_to_role, and roles model.

users model

	public function getRoleAttribute()
	{
		return $this->user_to_role->role;
	}

    public function user_to_role()
    {
        return $this->hasOne(UserToRole::class, 'user_id');
    }

user_to_role model

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')
                    ->withTrashed();
    }

    public function role()
    {
        return $this->belongsTo(Roles::class, 'role_id')
                    ->withTrashed();
    }

roles model

    public function user_to_role()
    {
        return $this->hasMany(UserToRole::class, 'role_id');
    }

now you can call from user model :

Auth::user()->role->id

automica's avatar
automica
Best Answer
Level 54

@gzai defining your intermediate table with its own model is a bit unconventional. Its not necessary.

@paulcatalin97

To follow convention, your join table should be called role_user

You can then define the following:

  • User belongsToMany Role
// User

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

// Role

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

and then on your User model you can add the following:

public function hasRole(...$roles)
    {
        foreach($roles as $role)
        {
            if($this->roles->contains('name', $role))
            {
                return true;
            }
        }
        return false;
    }

which will allow you to check

if(Auth::user()->hasRole('admin')){
          // do something
        }

You shouldn't use ids for Roles within your system. Stick to the roles name as that won't change.

2 likes

Please or to participate in this conversation.