DavidMathews's avatar

OrderByRaw with Pagination

Does anyone have an example of a working orderByRaw working with Pagination?

The first page is ordered correctly but any page clicked in the pagination returns the collection without the orderByRaw applied....

0 likes
1 reply
LaryAI's avatar
Level 58

One possible solution is to pass the orderByRaw clause to the paginate method instead of chaining it after the query. Here's an example:

$users = DB::table('users')
    ->orderByRaw('FIELD(status, "active", "pending", "disabled")')
    ->paginate(10);

This should apply the orderByRaw clause to all pages of the pagination.

Please or to participate in this conversation.