Sorting in Laravel: Sort by different columns (first by integers, then by strings)
P粉124890778
P粉124890778 2024-03-30 23:23:54
0
1
414

I am listing items ordered by device.sort_order integer column and that column is working fine.

$parts = \App\DevicePart::with('device')->get()->sortBy('device.sort_order')->values();

@foreach($parts as $i)
  {{ $i->device->sort_order }} - {{ $i->title }}
@endforeach

This will produce a list that looks like this:

1 - Carga
1 - Baseband
2 - Baseband
2 - Conectores
2 - Camera

So, now I want to sort it a second time by the title field without losing the first order, so the ITEM TITLES can be displayed in alphabetical order.

1 - Baseband
1 - Carga
2 - Baseband
2 - Camera
2 - Conectores

Is there any way to do this?

P粉124890778
P粉124890778

reply all(1)
P粉099985373

Use ORDER BY sort_order, title, its equivalent in Laravel is:

$parts = \App\DevicePart::with('device')
    ->orderBy('sort_order')
    ->orderBy('title')
    ->get();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template