thomhurks/laravel-collection-extensions

Extensions for Laravel's Collection class. Notably groupByMultiple for grouping collections on multiple fields instead of just one.
104 5
Install
composer require thomhurks/laravel-collection-extensions
Latest Version:v1.0.1
PHP:>=5.6.29
License:MIT
Last Updated:Mar 21, 2017
Links: GitHub  ·  Packagist
Maintainer: ThomHurks

laravel-collection-extensions

Extensions for Laravel's Collection class. Notably groupByMultiple for grouping collections on multiple fields instead of just one.

Example:

A B C D
foo bar baz thud
foo garply corge plugh
foo bar corge thud
foo bar corge waldo
qux garply xyzzy fred
qux grault garply quuz

By calling myCollection->groupBy(['A', 'B', 'C', 'D']) the result would become:

  • foo
    • bar
      • baz
        • thud [foo, bar, baz, thud]
      • corge
        • thud [foo, bar, corge, thud]
        • waldo [foo, bar, corge, waldo]
    • garply
      • corge
        • plugh [foo, garply, corge, plugh]
  • qux
    • garply
      • xyzzy
        • fred [quz, garply, xyzzy, fred]
    • grault
      • garply
        • quuz [qux, grault, garply, quuz]

Cross compatibility The groupByMultiple function is somewhat compatible with Laravel's original groupBy in that it functions in the same way if you pass as first argument something that is not an array, so just like groupBy you can call it with a string or a closure. The function just puts the first argument in an array if it isn't one. If you try to pass a callable as an array, so ["Foo", "Bar"] where Foo::Bar() is a valid method, then of course the groupByMultiple function will just attempt to group on the key "Foo" first and "Bar" second; this is the main incompatibility with groupBy(). Of course you can pass an array with a callable in it, so [["Foo", "Bar"]] or [["Foo", "Bar"], "Baz"] would work just fine. For people already using groupBy, this function will be very easy to switch to.

Related Packages

lorisleiva/lody

Load files and classes as lazy collections in Laravel.

8,591,073 95
propaganistas/laravel-helper-macros

Useful helpers and macros for Laravel 5.

63 16
gamez/typed-collection

Type-safe collections based on Laravel Collections

372,175 45
isswp101/collection

This package allows you to update laravel collections by query

6 1
webfactorybulgaria/nestablecollection

A Laravel Package that extends Collection to handle unlimited nested items follo...

509 0