An example of custom pagination for Laravel Eloquent. In this scenario we have a model with a column (e.g. date
) which we want to use to group records with for pagination but at the same time we still want to work with separate entities in the view.
The trait replaces QueryBuilder
with a custom class which overrides forPage
method used for pagination. It normally adds OFFSET
and LIMIT
parameters to the query which limit the number of results for a particular page. In our case though we are quering the datasource first for values of the defined groups and getting the minimum and maximum values to use them in the pagination query instead of LIMIT
and OFFSET
. We are also removing defined groups for the final query, so the pagination will use grouped dataset while results will be individual records.
After setting up the trait in a model you simply call paginate()
. If no groups are defined the original forPage()
method will be used instead.
Example:
class Stats extends BaseModel
{
use GroupByPagination;
protected $dates = [
'date'
];
protected $perPage = 7;
}
Stats::groupBy('date')->orderByDesc('date')->paginate();
Thanks! Work for me with added
$clone->select($this->groups);
to runPaginationCountQuery: