Navigate Collections Easily in Laravel Using before() and after()
Laravel Collection's before() and after() methods allow you to retrieve items immediately before or after a given value. These methods simplify navigation through ordered collections without worrying about array indexes.
Imagine a ticket status workflow:
$statuses = collect([
'Open',
'Assigned',
'In Progress',
'Resolved',
'Closed',
]);
Current status:
$current = 'In Progress';
Previous status:
$statuses->before($current);
Result:
Assigned
Next status:
$statuses->after($current);
Result:
Resolved
Using a Callback
You may also use a callback:
$users = collect([
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 3, 'name' => 'Mike'],
]);
$users->after(fn ($user) => $user['id'] === 2);
Result:
[
'id' => 3,
'name' => 'Mike',
]
Why Use before() and after()?
They help you:
- Avoid manual array indexes
- Navigate workflows easily
- Build multi-step forms
- Handle previous and next records cleanly
When to Use Them
Use these methods for:
- Order statuses
- Workflow steps
- Navigation menus
- Multi-step processes
- Timeline events