How to populate a checkbox dynamically with Laravel Eloquent

I have a user and a role two tabular data, I retrieve the data using eloquent and send to my view. Now I want to dynamically populate the user role checkbox. at this time I wrote as hard code

Here is my code.

@foreach($users as $user)
    <tr>
        <td>{{$user->name}}</td>
        <td>{{$user->email}}</td>

         @foreach($user->roles as $role)

        <td><input type="checkbox" name="" {{$user->hasRole('User') ? 'checked' : ''}}></td>
        <td><input type="checkbox" name="" {{$user->hasRole('Admin') ? 'checked' : ''}}></td>
        <td><input type="checkbox" name="" {{$user->hasRole('Author') ? 'checked' : ''}}></td>
         @endforeach
        <td></td>
    </tr>
    @endforeach

My unusual request.

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

    return view('admin',compact('users'));

User model relationships.

 public function roles()
{
    return $this->belongsToMany('App\Role');
}
+4
source share
1 answer

In the controller, you also need to load all the roles:

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

And in the view, do something like this:

@foreach($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->email }}</td>

        @foreach($roles as $role)
            <td><input type="checkbox" name="role[]" {{ $user->roles->contains($role) ? 'checked' : '' }}></td>
        @endforeach
        <td></td>
    </tr>
@endforeach

So, you need to iterate over all roles, not just the roles that the user has.

0
source

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


All Articles