Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ordering results by specific values

I have this line of code which gets results from a database:

'clanMembers' => User::find(Auth::user() -> clan_id) -> where('clan_id', '=', Auth::user() -> clan_id) -> orderBy('username') -> get()

Currently it orders by the username. I wish to change this to order by the clan_rank field. This clan_rank field will only ever contain 3 different values. These are:

1. Owner
2. Admin
3. Member

I wish to have my results ordered with Owners first, then Admin, then members. How can I change my line of code to achieve these results?

like image 953
Darryl Chapman Avatar asked Sep 25 '14 18:09

Darryl Chapman


People also ask

How to sorting data in Laravel?

To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.

How do you set a specific order in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Can we use like in order by in SQL?

On another hand, the ORDER BY keyword allows you to sort the result-set in ascending or descending order based on a specific column. But the ascending or descending order is not useful on a search result with the LIKE operator. Because the result-set will not be relevance with ORDER BY in MySQL.

What is all () in laravel?

all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.


1 Answers

You need to use orderByRaw:

instead of orderBy part you should use

orderByRaw("FIELD(clan_rank , 'Owner', 'Admin', 'Member') ASC");
like image 155
Marcin Nabiałek Avatar answered Oct 22 '22 11:10

Marcin Nabiałek