Skip to content

Instantly share code, notes, and snippets.

@Braunson
Last active October 24, 2019 20:40
Show Gist options
  • Save Braunson/d2c971e81e45234dc2d9ca08a6c9e5e7 to your computer and use it in GitHub Desktop.
Save Braunson/d2c971e81e45234dc2d9ca08a6c9e5e7 to your computer and use it in GitHub Desktop.
Laravel Collection Macro trimEndWhile
Collection::macro('trimEndWhile', function ($callback) {
$collection = new static($this->items);
while ($collection->count() && $callback($collection->last()) {
$collection->pop();
}
return $collection;
});
// Usage
$result = collect([10, 20, 30, 40, 50])->trimEndWhile(function ($i) {
return $i > 25;
});
// Returns
// [10, 20]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment