I have two Table names are User and Role Table. I have set manyTomany relations between them using pivot table name Role_User in Laravel Eloquent. Now, I want to show both table data in together a view using Eloquent Relationship.(e.g. I want to show in my view a user from users table contain which role in roles table )
Here, is my eloquent relations.
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function users()
{
return $this->belongsToMany('App\User');
}
My, Eloquent Relationship Query.
$users=User::with('roles')->get();
return view('admin',compact('users'));
I'm try in my View.
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->roles->name}}</td>
<td></td>
</tr>
@endforeach
When you call $user->roles
, you get a collection of the roles back. So if you want to display them all in a single string, all you have to do is implode the collection on that string:
<td>{{$user->roles->implode('name', ', ')}}</td>
Your $user->rules
is instance of Collection of Role model. You can use one more foreach:
@foreach($users as $user)
//do something with user
@foreach($user->roles as $role)
{{$role->name}}
@endforeach
@endforeach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With