How to fill the form checkboxes with checked data from database laravel 5.8

945 Views Asked by At

I'm having a problem in my update Form,

I create user with multiple roles assigned using checkboxes in my form, and when I need to update a user i get all the data into my update form input fields except the checkbox fields will be empty. Is there a way that I can get the checkbox checked with the data from database ?

Here's my User Model Relationship

public function roles()
{
    return $this->belongsToMany(Role::class)->withTimestamps();
}

Here's my Role Model Relationship

public function users()
{
    return $this->belongsToMany(User::class)->withTimestamps();
}

Here's my Edit User Form

<form action="{{ route('users.update',['user'=>$user]) }}" method="POST">
        @method('PATCH')
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" name="name" class="form-control" value="{{ old('name') ?? $user->name }}">
                <span class="text-danger">{{ $errors->first('name') }}</span>
            </div>

            <div class="form-group">
                <label for="email">Email</label>
                <input type="text" name="email" class="form-control" value="{{ old('email') ?? $user->email }}">
                <span class="text-danger">{{ $errors->first('email') }}</span>
            </div>

            <div class="form-group">
                @foreach ($roles as $role)
                <label for="role">{{ $role->name }}</label>
                    <input type="checkbox" name="role[{{$role->id}}]" value="{{ old($role->id) }}"
                    @if(in_array($role->id,old('role',[]) )) checked @endif >
                @endforeach
                <span class="text-danger">{{ $errors->first('role') }}</span>
            </div>

            @csrf
            <button class="btn btn-primary" type="submit">Create</button>
    </form>

Here's my Edit Function

 public function edit(User $user)
    {
        $roles = Role::all();
        return view('users.edit', compact('user', 'roles'));
    }

I just wanted to know how can I pull data into my checkboxes from the database and mark them as checked

2

There are 2 best solutions below

0
On BEST ANSWER

Finally I found out the answer

<div class="form-group">
    @foreach ($roles as $role)
      <label for="role">{{ $role->name }}</label>

      <input type="checkbox" name="role[]" value="{{ $role->id }}"
      {{ $role->users->contains($user->id) ? 'checked' : '' }}
      @if(in_array($role->id,old('role',[]))) checked  @endif>

   @endforeach
     <span class="text-danger">{{ $errors->first('role') }}</span>
 </div>
0
On

I guess you should check role id with the user role id:

@if(in_array($role->id, $user->roles->toArray())) checked @endif