Laravel Collection Public API: take

November 30, 2016 —John Koster

take($limit)

The take method is a useful method that will return a number of items (up to the provided $limit) from the collection. If the $limit is negative, it will return a number of items (up to the provided $limit) from the end of the collection, otherwise the items will be returned from the beginning of the collection. The take method returns a new Collection instance and does not modify the original collection.

The following example demonstrates the usage of the take method:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third', 'fourth'
8]);
9 
10// Take two items from the beginning of the collection.
11$positiveLimit = $collection->take(2);
12 
13// Take two items from the end of the collection.
14$negativeLimit = $collection->take(-2);

After the above code has executed both $positiveLimit and $negativeLimit will be an instance of Collection. The $positiveLimit variable will contain a value similar to the following output:

1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)

And the $negativeLimit variable will contain a value similar to the following output:

1object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'third' (length=5)
5 1 => string 'fourth' (length=6)

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.