Search code examples
phplaravelmany-to-manylaravel-blade

Laravel - how to display data of two tables using their pivot table


There are three tables:

- users (id, name,email,password)

-roles(id, name)

-user_roles(user_id,role_id)

What I am trying to do

Get the user_id from user_roles and using a foreach loop, display which role_id are assigned from role to it e.g.

John Doe | Manager

Jane Doe | Admin

EDIT: In response to Andy Holmes comment below:

In User model, the following relationship exists, with an inverse in the Role model.

public function roles(){
        return $this->belongsToMany('App\Role')->withTimestamps();
    }

Solution

  • If I understand the scenario correctly, you should be able to access this directly from your Model's Relationship.

    You can do the following to access the user's role information:

    $user->roles and place this inside your loop