How to show two data tables in a view using Laravel's "Human Relationships"

I have two table names: User and Table Role . I have established many relationships between them using the Role_User pivot table name in Laravel Eloquent. Now I want to show both tabular data along with a view using Eloquent Relationship. (For example, I want to show, in my opinion, the user from the user table contains a role in the cast table)

Here are my eloquent relationships.

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

My request for explicit affection.

  $users=User::with('roles')->get(); return view('admin',compact('users')); 

I try in my presentation.

  @foreach($users as $user) <tr> <td>{{$user->name}}</td> <td>{{$user->email}}</td> <td>{{$user->roles->name}}</td> <td></td> </tr> @endforeach 
+5
source share
2 answers

When you call $user->roles , you get a collection of roles. Therefore, if you want to display them all on one line, all you have to do is break the collection into this line:

<td>{{$user->roles->implode('name', ', ')}}</td>

+1
source

Your $user->rules is an instance of the Collection of Role model. You can use another foreach:

 @foreach($users as $user) //do something with user @foreach($user->roles as $role) {{$role->name}} @endforeach @endforeach 
0
source

Source: https://habr.com/ru/post/1274839/


All Articles