Search

Laravel 5 Collections: Retrieving a Specified Number of Items From a Collection With take

April 22, 2018 —John Koster

The take method is a useful method that will return the provided 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.

#Signature

1public function take(
2 $limit
3);

#Example Use

The following example demonstrates the usage of the take method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third', 'fourth'
6]);
7 
8// Take two items from the beginning of the collection.
9$positiveLimit = $collection->take(2);
10 
11// Take two items from the end of the collection.
12$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)
2 protected 'items' =>
3 array
4 0 => string 'first'
5 1 => string 'second'

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

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 0 => string 'third'
5 1 => string 'fourth'

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.