Reputation: 5107
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?
Upvotes: 6
Views: 11181
Reputation: 4821
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
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
Upvotes: 10