Search code examples
phplaravelcheckboxlaravel-5laravelcollective

Laravel | Checkbox state on edit page


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


Solution

  • 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.