Add pagination with findwhere collection on Laravel l5 repository system

Now a days 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 opportunity to use paginate like this -


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

Sometimes we have 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 error message. Cause we can not use paginate with collection.

To use paginate we can use like this. First declare these two packages.
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

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);

On 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 collection.

Comments

Popular Posts

Install and configure Network simulator (ns3) on Ubuntu 14.04