Add pagination with findwhere collection on Laravel l5 repository system

October 20, 2016

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

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

2 Comments. Leave new

Excelente post!! Ajudou muito!!

Oliver Russell
October 23, 2018 4:45 pm

For Laravel pagination ( ), the best method is to call paginate() from eloquent. This method is pretty simple and quick to implement. You can don’t to write that much code for this either.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.