I have an example table like the following:
| id | is_new | cate |
| 0 | 1 | [5] |
| 1 | 1 | [5] |
| 2 | 1 | [7] |
| 3 | 1 | [6] |
After I call the following function
$product = Products::where('is_new', 1)->get();
the collection has the following data structure
Collection {#1284 ▼
#items: array:4 [▼
0 => Products {#1285 ▶}
1 => Products {#1286 ▶}
2 => Products {#1287 ▶}
3 => Products {#1288 ▶}
]
}
I can also return a list of category id through:
$category = Category::where('type', 2)->pluck('id')->all();
I wonder is there any good way to achieve following structure (or similar) based on cate. I can use brute force way to create it by looping through the $category then add to new collection manually, I think there is a better way to do it.
Collection {#1284 ▼
#items: array:3 [▼
5 => array:2 [▼
0 => Products {#1285 ▶}
1 => Products {#1286 ▶}
]
6 => Products {#1287 ▶} or 6 => array:1 [ 0 => Products {#1287 ▶} ]
7 => Products {#1288 ▶}
]
}
Solution Update based on answer:
$product->groupBy(function($item) {
return $item['cate'][0]; //because the entry is a list
});
You should take a look at using something like groupBy
to group your categories together. It can be done on a database level (assuming you have referential integrity) with foreign keys. You'll also get a guarantee that what is returned is an array for each category, which will make things more consistent (you won't need to make a check for if it is an array or an instance of Products
, then).
You might need to change your database layout if your categories are stored like arrays, but for this you should use an intermediary table - look at many to many relationships.