Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique/distinct in laravel foreach

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?

like image 962
Geoff_S Avatar asked Mar 08 '23 15:03

Geoff_S


1 Answers

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
like image 124
ntzm Avatar answered Mar 15 '23 02:03

ntzm