How to find an available collection [Laravel 4.2]

Let's say I have 200 records in my DB. When showing these posts, I want to paginate them. The usual approach would be to do something like

$tasks = Tasks::paginate(10); 

      

Then

$tasks->links();

      

This code works fine. However, with this code, you will run a DB query every time you fetch those 10 rows (200/10 = 20 times for all rows).

I need to collect all the data in one go, store it in a collection (say $tasks

), then paginate resulting collection

instead of fetching it from the database again.

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

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

      

but unfortunately even that doesn't work.

Anyone with an idea on how to solve these problems?

+3


source to share


1 answer


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

      

To get different task pages, you need to create new Paginator objects, as they do not store the entire set of tasks, only the current page.

Laravel 4



The Paginator in Laravel 4 does not seem to "handle pagination", that is, it expects you not to pass all the elements, but only the elements from the current page. In L5, you can pass all the elements and the current page, and Paginator will handle everything for you.

To use Paginator in L4, you need to slice the arra of tasks first and then use the Paginator facade (which uses the Illuminate \ Pagination \ Factory internally) to create the 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 if a Paginator built this way would be of any use to you.

+1


source







All Articles