Skip to main content
Back to packages
1,906 GitHub stars

spatie/laravel-collection-macros

View on GitHub

Description

A set of useful Laravel collection macros

Macros

  • after
  • at
    • second
    • third
    • fourth
    • fifth
    • sixth
    • seventh
    • eighth
    • ninth
    • tenth
    • getNth
  • catch
  • chunkBy
  • collectBy
  • containsAny
  • containsAll
  • eachCons
  • extract
  • filterMap
  • firstOrPush
  • fromPairs
  • getCaseInsensitive
  • glob
  • groupByModel
  • hasCaseInsensitive
  • head
  • if
  • ifAny
  • ifEmpty
  • insertAfter
  • insertAfterKey
  • insertAt
  • insertBefore
  • insertBeforeKey
  • none
  • paginate
  • path
  • pluckMany
  • pluckManyValues
  • pluckToArray
  • prioritize
  • recursive
  • rotate
  • sectionBy
  • simplePaginate
  • sliceBefore
  • tail
  • try
  • toPairs
  • transpose
  • validate
  • weightedRandom
  • withSize

after

Get the next item from the collection.

$collection = collect([1,2,3]);
 
$currentItem = 2;
 
$currentItem = $collection->after($currentItem); // return 3;
$collection->after($currentItem); // return null;
 
$currentItem = $collection->after(function($item) {
return $item > 1;
}); // return 3;

You can also pass a second parameter to be used as a fallback.

$collection = collect([1,2,3]);
 
$currentItem = 3;
 
$collection->after($currentItem, $collection->first()); // return 1;

at

Retrieve an item at an index.

$data = new Collection([1, 2, 3]);
 
$data->at(0); // 1
$data->at(1); // 2
$data->at(-1); // 3

second

Retrieve item at the second index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
 
$data->second(); // 2

Recent Courses on Laravel Daily