Laravel Collection 'After' & 'Before' Methods

Jun 25, 2024

Two new amazing methods have been added to Laravel collection methods. The 'after' & 'before' methods give you the index before or after an index. Thanks to Ryuta for the PR.

$fruits = collect(['🍊', '🍎', '🍍']);
$apple = $fruits[1];

// after the apple
$fruits->after($apple); // '🍍'

// before the apple
$fruits->before($apple); // '🍊'

There are many scenarios where you may use the methods, here are some use cases:

// Form PR comments
$previousItem = $items->get($items->search($currentItem) - 1);
$nextItem = $items->get($items->search($currentItem) + 1);

// With the methods
$previousItem = $items->before($currentItem);
$nextItem = $items->after($currentItem);


Another use case was that I retrieved a previous date from a series of dates.

- $previousDate = $dates->get($dates->search($date) - 1);
- $nextDate = $dates->get($dates->search($date) + 1);

// with the methods
+ $previousDate = $dates->before($date);
+ $nextDate = $dates->after($date);