Fetching before and after items from a Laravel Collection
There would be this rare scenario where you would want to fetch the before and after values from a Laravel Collection. For instance, you’re using a collection to display a resource from it and want to go back and forth from that value in that collection.
A recent PR in Laravel solves this by introducing the before
and after
methods on the collection.
The before
method
The before
method returns the item before the given item in the collection.
$collection = collect([1, 2, 3, 4, 5]);
$collection->before(3); // 2
$collection->before(4); // 3
$collection->before(1); // null
$users = collect([
['name' => 'Bob', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'John', 'age' => 40],
]);
dump($users->before(fn ($value) => $value['age'] == 25));
// [ 'name' => 'Bob', 'age' => 30 ]
The method returns null if the given item is the first or not found.
The after
method
The after
method returns the item after the given item in the collection.
$collection = collect([1, 2, 3, 4, 5]);
$collection->after(3); // 4
$collection->after(4); // 5
$collection->after(5); // null
$users = collect([
['name' => 'Bob', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'John', 'age' => 40],
]);
dump($users->after(fn ($value) => $value['age'] == 25));
// [ 'name' => 'John', 'age' => 40 ]
The method returns null if the given item is the last or not found.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.