[9.x] Cursor pagination: convert original column to expression
Imagine you write the following query:
User::query()
->select('*')
->selectSub('CONCAT(firstname, \' \', lastname)', 'fullname')
->orderBy('fullname')
->orderBy('id')
->cursorPaginate()
According to the documentation, this should work:
Query expressions in "order by" clauses are supported only if they are aliased and added to the "select" clause as well.
But this query will only work when fetching the first page. When you fetch the users of the second page / next cursor, you will get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'CONCAT(firstname, ' ', lastname)' in 'where clause'
This is caused by the fact that the raw output of the getOriginalColumnNameForCursorPagination method is provided to a where method. This means that the original column value is interpreted as a real column name. That is not the case when aliasing a dynamic column.
By wrapping the result of the getOriginalColumnNameForCursorPagination method in an \Illuminate\Database\Query\Expression object, we ensure that the original column value is correctly interpreted.