Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Collection Macros Laravel Package

werxe/laravel-collection-macros

A handy set of macros that extends Laravel Collections with extra methods for common array and data transformations, letting you write cleaner, more expressive pipelines without custom helper functions or repetitive loops.

View on GitHub
Deep Wiki
Context7

Getting Started

  • composer require werxe/laravel-collection-macros. v7 requires Laravel 9.0+; if you're still on Laravel 8 you'll silently resolve v6.x — verify with composer show werxe/laravel-collection-macros after install.
  • No config to publish and no manual wiring: the service provider is auto-discovered and registers its macros onto Illuminate\Support\Collection at boot. Once installed, the helpers are available everywhere — including on Eloquent collections (User::all()->...), which is where most of the day-to-day value shows up.
  • Look first at: the README's macro table (that is the API surface), then the package's service provider to see exactly which macros get registered and which are skipped, then the individual macro files for the two or three you actually intend to use. Don't read the whole src/ tree up front.
  • First use case: multi-key sorting and reshaping in report/export code. Instead of chained sortBy closures or ->groupBy()->map() gymnastics, you write $orders->sortByMany(['status' => 'asc', 'created_at' => 'desc']) and move on. The second common entry point is transpose/rotate when turning result rows into columns for a pivot table or CSV.

Implementation Patterns

  • Slot into existing chains. Macros return collections or scalars, so they compose mid-pipeline: $rows->filterMap(fn ($r) => ...)->transpose()->map(...). Prefer this over extracting intermediate variables.
  • Pluck/map shortcuts. Helpers that collapse ->pluck('name', 'id')->toArray() into one call are the highest-frequency win in controllers and API resources.
  • Inline guards. ifAny / ifEmpty keep fallback logic inside the chain instead of forcing an if ($c->isNotEmpty()) block around it.
  • Eloquent + macro combos. Group models with a macro, then aggregate per group inside ->map(); this is much cleaner than each() with an external accumulator.
  • Co-locate app macros. Register your own Collection::macro() calls in a dedicated CollectionMacrosServiceProvider (or AppServiceProvider::boot()), not scattered across files — so vendor helpers and in-house helpers are discoverable in one place and boot order is predictable.
  • Wrap business-critical calls. If a macro sits in a revenue-affecting path, hide it behind an app-level helper or a small dedicated collection class. Swapping the package out later then becomes a one-file change.
  • Testing. Macros are runtime global state. (new Collection([...]))->macroName() works fine in unit tests; only call Collection::flushMacros() in tearDown if you genuinely need to assert on absence — it wipes other packages' macros too.
  • Blade. Fine for light formatting loops; move anything that reshapes data into a presenter or view model.

Gotchas and Tips

  • v7 BC break — Laravel 9 floor. Upgrade order matters: bump Laravel first, then the package, otherwise Composer resolves you back to v6 and nothing appears to change. Pin ^7.0 and treat major releases here as "check the Laravel requirement" releases.
  • Global monkey-patching. These are macros on the base Collection class, so collisions are the number-one failure mode. Laravel keeps absorbing good collection helpers natively — a name that was unique in Laravel 8 may be a first-class method in 9/10/11, in which case the native method wins and your macro appears to do nothing.
  • Debug registration order. Two packages (or the package and your app) registering the same macro name resolve by boot order, last-wins unless guarded. Before debugging your own code, check Collection::hasMacro('name') and grep composer.json for other collection-macro packages.
  • $this shadowing. Inside a macro closure $this is the collection instance, not your controller or service. Capture outer state explicitly with use ($var).
  • No static analysis. Macros are invisible to IDEs and PHPStan. Add @method docblocks on a stub class or use laravel-ide-helper, or every call site is a squiggle with no jump-to-definition.
  • Keep registration non-deferred. config:cache/route:cache don't affect macro registration, but a deferred provider that registers macros lazily will bite you if anything calls the macro before the provider resolves.
  • Find the real implementation. Collection::hasMacro($name) plus a ReflectionFunction on Collection::getMacro($name) tells you whether you're hitting the package or an app override — faster than reading stack traces.
  • Extend, don't fork. When the package lacks a variant you need, layer a wrapper macro (Collection::macro('mySortMany', fn (...) => $this->sortByMany(...))) so app-specific rules stay in your codebase and survive package upgrades.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin