In laravel, I have a dropdown select box with some values, but my foreach loop around the box is showing every instance of $psku->frame_desc
, as it should. However, I want it to only show distinct values.
Here's the code:
<select style="margin-top:10px; max-width:200px;" >
<option value="" selected data-default>Sort by type:
</option>
@foreach ($orderFormData->pgroups as $pgroup)
@foreach ($pgroup->pskus as $psku)
<option value="{{ $psku->frame_desc }}">{{ $psku->frame_desc }}</option>
@endforeach
@endforeach
What's the best way to declare distinct or unique values within a foreach like this in laravel?
Assuming these are collections, you can do:
@foreach ($orderFormData->pgroups as $pgroup)
@foreach ($pgroup->pskus->unique('frame_desc') as $psku)
<option value="{{ $psku->frame_desc }}">{{ $psku->frame_desc }}</option>
@endforeach
@endforeach
Documentation
If they are not collections, you can make them collections:
@foreach ($orderFormData->pgroups as $pgroup)
@foreach (collect($pgroup->pskus)->unique('frame_desc') as $psku)
<option value="{{ $psku->frame_desc }}">{{ $psku->frame_desc }}</option>
@endforeach
@endforeach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With