Laravel | Checkbox state on edit page

10,136

Solution 1

The quick answer

 @foreach($services as $service)
      <input type="checkbox" name="services[]" value="{{ $service->id }}"
           @if (count($case->services->where('id', $service->id)))
               checked
           @endif>
 @endforeach

I'm assuming you have a many to many eloquent relationship between Cases and Services. So that where is a collection method, not a query builder. If it finds nothing, it will return an empty collection, which is truthy by itself (hence the count function).

But for a more concise approach, if you're just looking at one Case at a time, I would go ahead and get a simple array of all the Service IDs that the case has and pass it into the view.

 // The eloquent way
 $case_services = $case->services->toArray();

 // Otherwise, just query for all service IDs
 $case_services = DB::table('case_services')->where('etc...')

 // You'll end up with something like [24, 47, 103, 287]

Then in your view, you can just run something like

 @foreach($services as $s)
      <input type="checkbox" name="{{ $s->name }}" value="{{ $s->service_id }}"
           @if( in_array($s->service_id, $case_services) ) checked="1" @endif />
 @endforeach

I just like the second solution because it's easier to tell what's going on, and is more predictable to me.

Solution 2

This is sample code, you can do this, If you are using Blade template, then do this, 3rd parameter is true/false to checked/un-checked the checkbox

{!! Form::checkbox('agree', 1, ($model->checkbox ==1?true:null), ['class' => 'field']) !!}

here you are passing your model DB stored value to checkbox (in 3rd param)

Share:
10,136
nclsvh
Author by

nclsvh

Updated on June 28, 2022

Comments

  • nclsvh
    nclsvh almost 2 years

    I have a create page for a new Case in Laravel 5, where I can link services to the case. The services are checkboxes in my createCaseForm. The services are stored in the DB so I write to a ManyToMany table to have many Cases which have many services.

    Example: When I create case1, I check the boxes for service1 and service3. So now the manyToMany table is filled in correctly. Now when I go to the edit page for the case I want the checkbox1 and checkbox3 to be checked by default, because they are already linked in the manyToMany table.

    I know you can use something like Input::old('username'); for textfields, but I don't know how to do this for a checkbox.

    I do use LaravelCollective most of the time, but for these checkboxes I didn't. So preferably I would like a HTML solution, IF POSSIBLE ofcourse.

    Thanks