Nowadays repository system L5 repository is popular. Suppose we have some posts and want to show this posts on the admin panel. On there we need to add pagination. L5 gives an opportunity to use paginate like this –

$posts = $this->repository->paginate(10)

Add pagination with findwhere collection

Sometimes we have a complex query. For this reason, we need to use findWhere like this=>

$posts = $this->repository->findWhere($queryArray)

Now if we want to use paginate like this =>

 $posts = $this->repository->findWhere($queryArray)->paginate(10)

We will get an error message. Cause we can not use paginate with a collection.

To use paginate we can use like this. First, declare these two packages.

use IlluminatePaginationPaginator;
use IlluminatePaginationLengthAwarePaginator;

After then you can write code like this to add paginate on the controller section.

$posts = $this->repository->findWhere($queryArray);
$currentPage = Paginator::resolveCurrentPage() - 1;
$perPage = 10;
$currentPageSearchResults = $posts->slice($currentPage * $perPage, $perPage)->all();
$posts = new LengthAwarePaginator($currentPageSearchResults, count($posts), $perPage);

In the view section, we can use like this

{!! $posts->setPath('/example-path')->appends(Request::except('page'))->render() !!}

By this method, you can add pagination with a collection.

Contributor: Akhlasur Rahman, Nascenia

Published On: October 20th, 2016 / Categories: Blog, Web Design / Tags: , , , , /