Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show two table data in a view using Eloquent Relationship in Laravel

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
like image 787
Gabrielle-M Avatar asked Jan 20 '18 20:01

Gabrielle-M


Video Answer


2 Answers

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>

like image 163
Joel Hinz Avatar answered Sep 25 '22 19:09

Joel Hinz


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
like image 21
akaincore Avatar answered Sep 24 '22 19:09

akaincore