Search code examples
phplaravellaravel-bladelaravel-collection

How to make dropdown list ascending order in PHP Laravel


This code from product_listing.blade.php and here the dropdown filter. I need all the item name in ascending orde. Right now the list is in order how I can see it in a database table..

                                    <div class="box-title text-center">
                                        {{ translate('Filter by CarType')}}
                                    </div>
                                    <div class="box-content">
                                        <div class="filter-checkbox">
                                            <select class="form-control" data-placeholder="{{ translate('All CarType')}}" name="cartype" onchange="filter()">
                                                <option value="">Select CarType</option>
                                                @foreach (\App\CarType::all() as $cartype)
                                                    <option value="{{ $cartype->id }}" @isset($cartype_id) @if ($cartype_id == $cartype->id) selected @endif @endisset>{{ $cartype->name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>

Solution

  • You can use collection's sortBy() method:

                                        <div class="box-title text-center">
                                            {{ translate('Filter by CarType')}}
                                        </div>
                                        <div class="box-content">
                                            <div class="filter-checkbox">
                                                <select class="form-control" data-placeholder="{{ translate('All CarType')}}" name="cartype" onchange="filter()">
                                                    <option value="">Select CarType</option>
                                                    @foreach (\App\CarType::all()->sortBy('name') as $cartype)
                                                        <option value="{{ $cartype->id }}" @isset($cartype_id) @if ($cartype_id == $cartype->id) selected @endif @endisset>{{ $cartype->name }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>