Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 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.

Comments?