abixalmon@me.com's avatar

paginating group_by queries

I am sure most of you have faced this problem, where pagination returns wrong total, if you use group_by in your query.

I have created a simple solution, which i wanted to share for review.

$query = Movies::select('movies.*')->join('movie_casts', 'movies.id', '=', 'movie_casts.movie_id')->groupBy('movies.id');
$movies = $this->customPaginate($query, $query->get()->count(), 20);
    /**
     * @param $query \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
     * @param $total
     * @param $per_page
     * @return LengthAwarePaginator
     */
    public function customPaginate($query, $total, $per_page)
    {
        $current_page = Paginator::resolveCurrentPage() ? Paginator::resolveCurrentPage() : 1;
        $data = $query->paginate($per_page)->items();
        $pagination = new LengthAwarePaginator($data, $total, $per_page, $current_page, [
            'path' => Paginator::resolveCurrentPath(),
        ]);

        return $pagination;
    }

Is there a simpler way to do this? any feedback on existing code will be great!

0 likes
0 replies

Please or to participate in this conversation.