Skip to main content

Order Results by Specific Values with orderByRaw() in Laravel

When querying a database, there are times when you need to sort the results by a specific value or calculated value. The orderByRaw() method in both Query Builder and Eloquent can be used for this purpose. This method allows you to specify a MySQL raw statement to use for ordering the results.

The orderByRaw() method is a powerful tool that can be used to customize the order of results returned by a query. By providing a raw string as the value of the “order by” clause, it is possible to specify precisely how the results should be sorted. This can be especially useful when dealing with complex data structures.

In addition, the orderByRaw() method can be used to optimize performance by avoiding unnecessary ordering operations. As such, it provides considerable flexibility when it comes to ordering query results.

$sales = DB::table('sales')
->orderByRaw("FIELD(state , 'SENT', 'DRAFT', 'DONE', 'CANCEL') ASC")

$sales = Sale::orderByRaw("FIELD(state , 'SENT', 'DRAFT', 'DONE', 'CANCEL') ASC")

By continuing to use the site, you agree to the use of cookies.