5
votes

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
3

3 Answers

4
votes

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>

1
votes

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
0
votes

This will work in Laravel 5.0 and above If we have two Model User and Mark. Then Inside the User Model make a function for relation with Mark. Example

public function marks()
    {
        return $this->hasMany('App\Models\Mark');
    } 

So, If you want to display the User name will all his marks. Then inside the controller perform following way.

    public function getUserMarks(){

        $result = User::select('email', 'name')->where('email', '[email protected]')->with(['marks'])->get();
        return view('welcome', compact('results'));
    }