Laravel 5 Collections: Paginating Collections With forPage

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.

#Signature

1public function forPage(
2 $page,
3 $perPage
4);

#Example Use

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 array
4 0 => int 8
5 1 => int 9

#Using chunk to Achieve Similar Results

The 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 array
4 0 => int 8
5 1 => int 9

Some absolutely amazing
people

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.