The try() and catch() macros provide a way to handle exceptions within a collection chain. This behaves similarly to a database transaction: if an exception is thrown between try() and catch(), the collection reverts to its state as it was before the try() call.
- You can access the original collection inside the
catch block by passing it as a second parameter to the handler. - You can manipulate the collection within
catch by returning a new value.
$collection = collect(['a', 'b', 'c', 1, 2, 3])
->try()
->map(function ($item) {
throw new Exception();
})
->catch(function (Exception $exception, $collection) {
return collect(['d', 'e', 'f']);
})
->map(function($item) {
return strtoupper($item);
});
// Result: ['D', 'E', 'F']
$collection = collect(['a', 'b', 'c', 1, 2, 3])
->try()
->map(fn ($letter) => strtoupper($letter))
->each(function() {
throw new Exception('Explosions in the sky');
})
->catch(function (Exception $exception) {
// handle exception here
})
->map(function() {
// further operations can be done, if the exception wasn't rethrow in the `catch`
});