melihovv/collection-grouped-by-model
Collection Grouped By Model
This package allows easily group laravel collection by any php object (model, array/collection of models, etc), not only by scalars (strings, numbers, booleans).
Installation
Install via composer
composer require melihovv/collection-grouped-by-model
Usage
$posts = Post::all()
$postsGroupedByAuthor = (new CollectionGroupedByModel($posts))->groupByModel('author_id', 'author');
foreach ($postsGroupedByAuthor as $authorPosts) {
$authorPosts->model(); // returns posts' author
$authorPosts->collection(); // returns author's posts
}
Nested grouping: first group products by category, then by manufacturer.
$products = Product::all();
$groupedProducts = (new CollectionGroupedByModel($products))
->groupByModel('category_id', 'category')
->transform(function (CollectionGroupedByModel $productsGroupedByCategory) {
return $productsGroupedByCategory->groupByModel('manufacturer_id', 'manufacturer');
});
foreach ($groupedProducts as $categoryProducts) {
$categoryProducts->model(); // returns category
foreach ($categoryProducts->collection() as $manufacturerProducts) {
$manufacturerProducts->model(); // returns manufacturer
$manufacturerProducts->collection(); // returns products grouped by category and manufacturer
}
}
Group by several models
$posts = Post::all()
$postsGroupedByAuthorAndCategory = (new CollectionGroupedByModel($posts))
->groupByModel(function (Post $post) {
return "$post->author_id,$post->category_id";
}, function (Post $post) {
return [$post->author, $post->category];
});
foreach ($postsGroupedByAuthorAndCategory as $authorPostsInCategory) {
list($author, $category) = $authorPostsWithCategory->model();
// or using php 7.1 array destruction
[$author, $category] = $authorPostsWithCategory->model();
$authorPostsWithCategory->collection(); // returns author's posts in category
}
Security
If you discover any security related issues, please email amelihovv@ya.ru instead of using the issue tracker.
Credits
This package is bootstrapped with the help of melihovv/laravel-package-generator.
Related Packages
typicms/nestablecollection
A Laravel Package that extends Collection to handle unlimited nested items follo...
350,143
88
jcrowe/type-safe-collection
A thin wrapper around Illuminate/Collection that allows for enforcing type const...
9,222
4
webfactorybulgaria/nestablecollection
A Laravel Package that extends Collection to handle unlimited nested items follo...
509
0
Version History
| Version | Released | PHP | Laravel | License |
|---|---|---|---|---|
| 1.6.0 | >=7.2 | ^6.0| | MIT | |
| 1.5.0 | >=7.2 | ^6.0 | MIT | |
| 1.4.0 | >=7.0 | ~5.5.0| | MIT | |
| 1.3.0 | >=7.0 | ~5.5.0| | MIT | |
| 1.2.0 | >=7.0 | ~5.5.0| | MIT | |
| 1.1.0 | >=7.0 | ~5.5.0 | MIT | |
| 1.0.0 | >=7.0 | ~5.5.0 | MIT |