Order Results by Specific Balues with orderByRaw() in Laravel

There are some situations that require developers to sort database results by specific values or calculated values. orderByRaw() method will useful.

Both Query Builder and Eloquent in Laravel support this method to allow querying using a MySQL raw statement.

For example, our database has a sales table that contains a state field. This field only has 4 values: DRAFT, SENT, DONE, and CANCEL. We want to list sales following this order, SENT, DRAFT, DONE, CANCEL.

Table of Contents

Query Builder

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


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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

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

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.