rjcode
rjcode

Reputation: 1349

Checkbox selection with two foreach loops

I have below code for showing all taxes as checkboxes, I am using same form for editing taxes,

@foreach($taxes as $t)
   @foreach($grouptax_taxes as $tg)
   <label class="checkbox">
   <input type="checkbox" name="taxgroup_rate[]" {{ isset($taxgroup) && $t->tax_id == $tg->tax_id ? 'checked' : ''}} id="taxgroup_{{$t->tax_id}}" value="{{$t->tax_id}}">
   <span></span>{{$t->tax_name}} - {{$t->tax_rate}} &percnt; </label>
   @endforeach
@endforeach

Problem is that it repeats all taxes multiple times as grouptax_rate, I know it will do repeat, but not sure how to select only those checkboxes which values are in $grouptax_taxes and remaining $taxes should not be selected,

How can I do that?

Upvotes: 0

Views: 188

Answers (1)

Doro
Doro

Reputation: 357

For the checked if values are equal should be done inside the checkbox, i.e the foreach loop should only cover the checked

    @foreach($taxes as $t)
           <label class="checkbox">
           <input type="checkbox" name="taxgroup_rate[]" value="{{$t->tax_id}}"   id="taxgroup_{{$t->tax_id}}"
            @foreach($grouptax_taxes as $tg)
             {{ ($t->tax_id == $tg->tax_id)? 'checked' : ''}}
           @endforeach >
           <span>{{$t->tax_name}} - {{$t->tax_rate}}</span></label>
        @endforeach

Upvotes: 1

Related Questions