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?
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.
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.
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.
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.
You need to use orderByRaw
:
instead of orderBy
part you should use
orderByRaw("FIELD(clan_rank , 'Owner', 'Admin', 'Member') ASC");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With