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
$sales = DB::table('sales') ->orderByRaw("FIELD(state , 'SENT', 'DRAFT', 'DONE', 'CANCEL') ASC") ->get();
$sales = Sale::orderByRaw("FIELD(state , 'SENT', 'DRAFT', 'DONE', 'CANCEL') ASC") ->paginate(100);