Home > Net >  How to stack same database results based on multiple columns in a Laravel project?
How to stack same database results based on multiple columns in a Laravel project?

Time:09-22

In a Laravel project I have a shapes table that has the following columns:

width, height, weight, color_id

How can I 'stack' all the shapes that are the same with a matching width, height, weight and color?

So far, I've tried to use the groupBy method, but when I use multiple criteria, it puts the results in a collection inside of collection inside of collection etc.

$stacks = Shape::latest()->get()->groupBy(['width', 'height', 'weight', 'color_id']);

My overall goal is to get an array/collection with all available "stacks", and in every stack to have the objects that are matching. Any suggestions how to do this?

CodePudding user response:

You can specify a custom group name with groupBy so you can combine all the parameters:

$stacks = Shape::latest()->get()
     ->groupBy(fn ($item) => $item->width.'-'.$item->height.'-'.$item->weight.'-'.$item->color_id);

This should create groups like e.g. 100-200-300-red

  • Related