Laravel Blade Templating @foreach order
Asked Answered
S

3

19

Is there any way to sort @foreach loop in laravel blade?

@foreach ($specialist as $key)
  <option value="{{$key->specialist_id}}"> {{$key->description}}</option>
@endforeach

I wolud like to order by $key->description,

I know I can use order by in my controller,

->orderBy('description')

but the controller returns other values and those values must be sorted as well, so I need to order by in blade.

Sheeb answered 10/1, 2016 at 0:12 Comment(0)
T
48

Assuming that your $specialist variable is an Eloquent collection, you can do:

@foreach ($specialist->sortBy('description') as $oneSpecialist)
  <option value="{{ $oneSpecialist->specialist_id }}"> {{ $oneSpecialist->description }}</option>
@endforeach

Moreover, you could call your Eloquent model directly from the template:

@foreach (Specialist::all()->sortBy('description') as $oneSpecialist)
  <option value="{{ $oneSpecialist->specialist_id }}"> {{ $oneSpecialist->description }}</option>
@endforeach

Note that you are using a misleading variable name of $key in your foreach() loop. Your $key is actually an array item, not a key. I assume that you saw foreach ($array as $key => $value) syntax somewhere and then removed the $value?

Thump answered 10/1, 2016 at 7:35 Comment(1)
How to sort by a property in a pivot tableLegacy
M
1

I would suggest using a laravel collection. More specifically, the sortBy(). You can use either of these in your view or the controller that you are passing the data from. If the data is being passed by a model, be sure to use the collect() function before proceeding to use any of the others listed.

Hope this helps!

Mainstream answered 10/1, 2016 at 1:45 Comment(1)
how to write sortBy in view blade? just like $sorted = $collection->sortBy('price'); or need write in the javasctipt?Transience
I
1

Even if the order fails you can use ->values() to re-index the elements

$collection->sortBy('key')->values()
Ier answered 7/2, 2023 at 3:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.