Skip to content
Advertisement

How to always fetch a special category item data first in Laravel

Suppose I have a table named machine with 3 columns(id, name, company).

There are 5 data in that table.

01, A, XX
02, B, XX
03, C, XY
04, D, XX
05, E, YY

Here A,B,C,D,E are the machine name and XX,XY,YY are the company name.

Now I want to fetch data according to company wise and there a specific company’s data will come always first. For that I use groupBy with company.

SQL

select('*')
from('machine')
groupBy('company')
get()

Result

01, A, XX
03, C, XY
05, E, YY

But I want to retrieve data where XX company’s data will always come first like below format

    01, A, XX
    02, B, XX
    04, D, XX
    03, C, XY
    05, E, YY

How to do that ? Anybody can help please ? Thanks in advance.

Advertisement

Answer

You can order by whether the company name is XX or not, using a boolean condition in orderbyRaw:

->orderbyRaw("company = 'XX' DESC")

If you want to sort multiple companies in order, use a CASE expression:

->orderbyRaw("CASE company WHEN 'XX' THEN 1
                           WHEN 'XY' THEN 2
                           ELSE 3
              END")
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement