Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Populate Checkbox dynamically using Laravel Eloquent

Tags:

php

laravel

I have user and role two table data,I've fetch the data using eloquent and send to my view. Now, I want to populate user role checkbox dynamically. at this time which is I've written 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 Eloquent Query.

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

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

User Model Relationship.

 public function roles()
{
    return $this->belongsToMany('App\Role');
}
like image 887
Gabrielle-M Avatar asked Oct 26 '25 04:10

Gabrielle-M


1 Answers

In 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 and not just over roles that user has.

like image 176
Alexey Mezenin Avatar answered Oct 27 '25 18:10

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!