Skip to content

Instantly share code, notes, and snippets.

@AdenFraser
Last active April 28, 2018 21:57
Show Gist options
  • Save AdenFraser/c7a66a668cc4bbba20967de13324af23 to your computer and use it in GitHub Desktop.
Save AdenFraser/c7a66a668cc4bbba20967de13324af23 to your computer and use it in GitHub Desktop.
Laravel firstOr Collection Macro
<?php
use Illuminate\Support\Collection;
/*
* Get the first item. Performs callback if the item was not found.
*
* @return mixed
*/
Collection::macro('firstOr', function (callable $callback) {
if (! is_null($item = $this->first())) {
return $item;
}
return $callback();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment