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

Sonu's avatar
Level 3

Join Using Orm

I Have three tables Users,Roles,And Role_users

Now On role_users table i have both the ids of users as well as rolls user_id and role_id

Now i want to show records on a view page that which user has which rolls and their name etc..

0 likes
8 replies
Sonu's avatar
Level 3

@blackbird Here is table structure Users

id
name
email

Roles Table

id
name
slug
description

And 3rd Table role_user

id
role_id
user_id

At these 3 tables i have values of all in Db I want to show roles with their users at view page

bobbybouwmann's avatar
Level 88

Did you setup relations for your models?

BTW: You don't need the id attribute in the role_user table ;)

Sonu's avatar
Level 3

i mistakenly clicked on correct answer :(

Sonu's avatar
Level 3

@blackbird i want all users not using find How can i get all My User Model

protected $table = 'users';
    
     public function roles()
     {
        return $this->belongsToMany('App\Role');
     }

And I Here Is My Controller

$roles = User::find(3)->roles;
return view('assign_roles.view')->with('roles',$roles);

Using finds it works but i want all user not for specific id

bobbybouwmann's avatar

You want all users with their role right?

In your controller

public function users()
{
    $users = Users::with('roles')->get(); // return all users with their role

    return view('users', compact('users'));
}

Now you can do this in your view

@foreach ($users as $user)

    <h3>{{ $user->name }}</h3>
    <p>Role: {{ $user->role->name }}</p>

    <hr>

@endforeach

If this is not what you want you need to be more specific with your question!

1 like
Sonu's avatar
Level 3

@blackbird Trying to get property of non-object i got this error at my view :(

<p>Role: {{ $user->role->name }}</p>
bobbybouwmann's avatar

You called your function roles and not role so you need to update it to this

<p>Role: {{ $user->roles->name }}</p>

Please try to think a bit for yourself ;)

Please or to participate in this conversation.