search

Home  >  Q&A  >  body text

Sorting in Laravel: Sort by different columns (first by integers, then by strings)

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粉124890778P粉124890778264 days ago439

reply all(1)I'll reply

  • P粉099985373

    P粉0999853732024-03-31 17:09:15

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

    $parts = \App\DevicePart::with('device')
        ->orderBy('sort_order')
        ->orderBy('title')
        ->get();
    

    reply
    0
  • Cancelreply