April 22, 2018 —John Koster
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.
This method can be incredibly useful when implementing APIs for flat-file driven content management systems.
1public function forPage(2 $page,3 $perPage4);
The following example demonstrates the forPage
method:
1use Illuminate\Support\Collection; 2 3// Create a new collection instance. 4$collection = new Collection([ 5 0,1,2,3,4,5,6,7,8,9,10 6]); 7 8// Get the "fifth" page of the collection 9// assuming there are two items per page.10$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)2 protected 'items' =>3 array4 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.
1use Illuminate\Support\Collection; 2 3// Create a new collection instance. 4$collection = new Collection([ 5 0,1,2,3,4,5,6,7,8,9,10 6]); 7 8// Chunk the collection into smaller collections, 9// with each page containing two items.10$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// Get the fifth "page".2$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)2 protected 'items' =>3 array4 0 => int 85 1 => int 9
∎