1

I have two foreach loop nested, I only want the inner loop to check the condition. If it satisfies or not either one, then terminate the inner loop and come back to the outer loop.

In my condition, the inner loop always needs to run once as I understand my Problem.

Problem: Two arrays. First having all options. Second having only selected. Now math the id. If matched=> Print checked, Else => UnChecked.

I have tried the break; but inner loop only check 1st item then all iteration in else part executed.

@php
foreach($propertyAmenities as $amenity){
   foreach($property->amenities as $new){ 
        if( ($amenity->type == 'amenity') && ($amenity->id == $new->id) ){
        @endphp
        <label class="checkbox-inline control-label">
            <input type="checkbox" name="amenity[]" value="{{$amenity->id}}" {{'checked'}}>{{ $amenity->name }}
        </label>                         
        @php break;                       
          } 
        elseif(($amenity->type == 'amenity')){ @endphp
            <label class="checkbox-inline control-label">
                <input type="checkbox" name="amenity[]" value="{{$amenity->id}}">{{ $amenity->name }}
            </label> 
        @php break;
            }                                                                    
         }
      }
@endphp

First time it checks and print 'checked' next time its only execute ifelse part. i dont know why only first is checked.

all else remain Unchecked.

2
  • Is amenities in $property->amenities a relationship method? Commented Apr 14, 2019 at 14:33
  • yess it is a relationship Commented Apr 14, 2019 at 19:00

1 Answer 1

1

You can simplify your code by passing the selected options as array in the view.


// Given $selectedOptions = [1, 2, 3, 4...]
@foreach($property->amenities as $amenity)
    <label class="checkbox-inline control-label">
        <input type="checkbox" 
               name="amenity[]" 
               value="{{$amenity->id}}"
               @if (in_array($amenity->id, $selectedOptions))
                   checked="checked"
               @endif
        >{{ $amenity->name }}
    </label>  
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.