3
votes

Suppose I have 200 records in my DB. While displaying those records I want to paginate them. The normal approach would be doing something like

$tasks = Tasks::paginate(10); 

Then

$tasks->links();

That code works fine. However, With that code you are going to run DB query every time you fetch those 10 rows (200/10= 20 times for all rows).

What I need is to fetch all data at once, store them in a collection (say $tasks),Then paginate the resulting collection instead of fetching again from DB.

Even more, I need to query something like "Get only 100 records and paginate them by 10 " which would be nice if it would be something like

Tasks::take(100)->paginate(10) 

but unfortunately even that do not work.

Anyone with an idea on how to tackle these issues?

1

1 Answers

1
votes

Laravel 5

$tasks = Tasks::take(100); // fetch 100 tasks

// initialize paginator
$paginator = new \Illuminate\Pagination\Paginator($tasks, 10, $pageNumber); 

// get current page of tasks
$currentPage = $paginator->items();

In order to get different pages of tasks you'll need to create new Paginator objects, as it doesn't store the whole collection of tasks but only current page.

Laravel 4

It seems that Paginator in Laravel 4 doesn't "handle the pagination", meaning it expects you to pass not all the items but only items from current page. In L5 you could pass all items and current page and Paginator would handle everything for you.

In order to use the Paginator in L4 you'll need to slice the arra of tasks yourself and then use Paginator facade (that uses Illuminate\Pagination\Factory internally) to create Paginator object.

use Paginator;

$tasks = Tasks::take(100);
$currentPageTasks = $tasks->slice(($currentPage - 1) * $perPage, $perPage);
Paginator::make($currentPageTasks, $tasks->count(), $perPage);

I'm not sure though if Paginator built this way will be of any use to you.