November 29, 2016 —John Koster
forPage($page, $perPage)
The forPage
method is used to implement pagination over collections. The forPage
defines two parameters: $page
, which is used to tell the collection which "page" should be returned and $perPage
, which is used to control the number of items that should be on a given page. The forPage
method returns a new collection instance.
The following example demonstrates the forPage
method:
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 0,1,2,3,4,5,6,7,8,9,10 8]); 9 10// Get the "fifth" page of the collection11// assuming there are two items per page.12$fifthPage = $collection->forPage(5, 2);
The $fifthPage
variable will now contain an instance of the Collection
class and will have a value similar to the following output:
1object(Illuminate\Support\Collection)[134]2 protected 'items' =>3 array (size=2)4 0 => int 85 1 => int 9
chunk
To Achieve Similar ResultsThe chunk
method can be used to achieve similar results. The following code sample will use the same collection from the previous example, and chunk it into smaller collections each containing two items.
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 0,1,2,3,4,5,6,7,8,9,10 8]); 9 10// Chunk the collection into smaller collections,11// with each page containing two items.12$pages = $collection->chunk(2);
The $pages
variable is also an instance of Collection
and contains other collections representing our pages, each with two items. The get
method can be used to retrieve the fifth page (4
is passed because the keys of the collection are zero-based):
1<?php2 3// Get the fifth "page".4$fifthPage = $pages->get(4);
Like before, the $fifthPage
will be an instance of Collection
and will have a value similar to the following output:
1object(Illuminate\Support\Collection)[138]2 protected 'items' =>3 array (size=2)4 0 => int 85 1 => int 9
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.