PHP code example of melihovv / collection-grouped-by-model
1. Go to this page and download the library: Download melihovv/collection-grouped-by-model library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
melihovv / collection-grouped-by-model example snippets
$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
}
$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
}
}
$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
}