Home > database >  Get multiple child records as a list in each row MySql
Get multiple child records as a list in each row MySql

Time:09-07

DB Schema

I have users table each user has multiple roles. I want to show a list of users and in list all roles of each user. Like user1 has admin, and supervisor role then show 1 row for user 1 and in roles field show admin, supervisor Frontend View

I am working on laravel. Tried through model relationship

public function roles(){

    return $this->belongsToMany('App\Models\UserRole');
}

Fetching...

    $users = User::all();
    $roles = $users->roles;
    return $users;

Also tried

$users->roles();
Users::roles();

none is working... It says roles is not defined...

CodePudding user response:

Fetching...

$users = User::with('roles')->get();
return $users;

Show users in table.

@foreach($users as $user)
    <tr>
        <td>{{ $user->username }}</td>
        <td>{{ $user->name }}</td>
        <td>{{ $user->email}}</td>
        <td>
            @foreach($user->roles as $role)
                {{ $role->name }}
                {{ $loop->iteration == $loop->count ? ', ':'' }}
            @endforeach
        </td>
        <td>Your actions</td>
    </tr>
@endforeach
  • Related