spatie/laravel-collection-macros
Adds a curated set of handy macros to Laravel Collections, extending them with extra helper methods (e.g., positional accessors like second/third, after, getNth, and more). Auto-registers via Composer for quick, drop-in productivity boosts.
Install the package with composer require spatie/laravel-collection-macros. No service provider registration is needed—Laravel auto-discovers it. Start by exploring commonly needed operations that aren’t in core Collections: grouping by models (groupByModel), case-insensitive lookups (getCaseInsensitive/hasCaseInsensitive), or concise fallback-handling (firstOrPush, ifEmpty). The README provides self-contained usage examples for each macro—begin with a few that solve your current pain points (e.g., filterMap for “map then remove nulls”, extract for destructuring lists from collections), then gradually adopt others as you notice repetitive patterns.
if, ifAny, ifEmpty, filterMap, or firstOrPush. For example, replace if ($items->isEmpty()) { $items->push($fetched); } with $items->firstOrPush(fn($i) => $i === $id, $fetched).extract for destructuring (e.g., [$title, $author] = $book->extract('title', 'author.name')), fromPairs/toPairs for pair conversions, and transpose for matrix operations.groupByModel) when working with related collections instead of raw groupBy('category_id').ifAny to conditionally log or track, or ifEmpty to seed a fallback—keep pipelines fluent.getCaseInsensitive/hasCaseInsensitive for user input or inconsistent external APIs.chunkBy for continuous grouping (e.g., segment by state change), eachCons for sliding window operations, or sliceBefore for splitting on delimiters.pluckMany return arrays, while others return Collections—check the return type to avoid chaining errors.extract uses null for missing keys (unlike only, which omits them); remember this when destructuring and strictness matters.get.firstOrPush requires explicit target collection if you want to push to the same collection and mutate—it’s not automatic. Pass the collection as the third argument.'user.name') where supported (extract, getCaseInsensitive), but verify per-macro docs.How can I help you explore Laravel packages today?