arnabrahman's avatar

Laravel manual pagination

I've a collection. I want to use manual pagination to show this in my view. Can anyone give me an example

0 likes
3 replies
zachleigh's avatar
Level 47

I do this:

    /**
     * Paginate answers.
     *
     * @param array $answers
     *
     * @return LengthAwarePaginator
     */
    protected function paginateAnswers(array $answers, $perPage = 10)
    {
        $page = Input::get('page', 1);

        $offset = ($page * $perPage) - $perPage;

        $paginator = new LengthAwarePaginator(
            $this->transformAnswers($answers, $offset, $perPage),
            count($answers),
            $perPage,
            $page,
            ['path' => $this->request->url(), 'query' => $this->request->query()]
        );

        return $paginator;
    }

    /**
     * Transform answers.
     *
     * @param array $answers
     * @param int $offset
     * @param int $perPage
     *
     * @return array
     */
    private function transformAnswers($answers, $offset, $perPage)
    {
        $answers = array_slice($answers, $offset, $perPage, true);

        return $this->transformer->toResult(collect($answers));
    }

On the line that reads $this->transformAnswers($answers, $offset, $perPage), you could just put $answers = array_slice($answers, $offset, $perPage, true);, but I use a transformer service to transform the answers first.

arnabrahman's avatar

@zachleigh Thanks, i did similar to yours.

//Get current page form url e.g. &page=2, at default 1
$currentPage=Input::get('page',1);

//Define how many items to show in each page
$perPage = 5;

//Slice the collection according to per page
$currentPageResults = $products->slice(($currentPage-1)*$perPage,$perPage)->all();

//Create the paginator and pass it to the view
$paginatedResults= new LengthAwarePaginator($currentPageResults, count($products),$perPage,$currentPage,['path'=>$request->url(),'query'=>$request->query()]);

return view('layouts.productlist', ['products'=>$paginatedResults];

Also had to render like this because it was adding an extra '/'

{!! str_replace('/?', '?',$products->render()) !!}

Please or to participate in this conversation.