Reputation: 7618
I'm using Laravel 5 for my project and I have this function to paginate the results:
return $query->approvate()->with( 'voti' )->get()->sortBy( function ( $sort )
{
return $sort->voti->count();
}, 0, true );
I have tried to use paginate()
but I need the results of the collection to be ordered before the pagination.
In Laravel 4 there was this method that has been removed in Laravel 5:
$paginator = Paginator::make($items, $totalItems, $perPage);
How can I paginate the results in L5 after the ordering?
Upvotes: 2
Views: 1630
Reputation: 166
Laravel has no way of paginating a collection, but I wrote a helper so you can still do this.
Try this code:
<?php
namespace Helpers;
use Illuminate\Support\Facades\Input;
class Paginator extends \Illuminate\Database\Eloquent\Collection {
private $pageNr;
private $perPage;
private $all;
public function paginate($perPage)
{
$this->perPage = (int) $perPage;
$this->pageNr = (int) $this->getCurrentPage();
$this->all = $this->all();
$this->items = array_slice($this->all(), $this->getCurrentPage()*$perPage-$perPage, $this->perPage);
return $this;
}
public function getCurrentPage()
{
$input = Input::get('page');
if($input==null)
return 1;
return $input;
}
public function getLastPage()
{
return(intval(ceil(count($this->all)/$this->perPage)));
}
public function getUrl($page)
{
return url('zoeken?page='.$page);
}
}
You might need to change the getUrl function.
Usage:
$paginator = new \Helpers\Paginator(Collection $col);
$paginator->paginate(int $x);
Upvotes: 2