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..
Did you setup a relation between the models? If not take a look at this: http://laravel.com/docs/5.0/eloquent#relationships
If this breaks your brain then we need to see your table structure so we can help you setup the relations! (the migrations would be fine for the database structure)
@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
Did you setup relations for your models?
BTW: You don't need the id attribute in the role_user table ;)
i mistakenly clicked on correct answer :(
@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
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!
@blackbird Trying to get property of non-object i got this error at my view :(
<p>Role: {{ $user->role->name }}</p>
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 sign in or create an account to participate in this conversation.