Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by size category as separate array in laravel php

Tags:

php

laravel-5

I have on table size_chart

| id | category | size | created_at          | updated_at | deleted_at |
+----+----------+------+---------------------+------------+------------+
|  1 | Regular  | S    | 2017-10-11 09:35:14 | NULL       | NULL       |
|  2 | Regular  | XS   | 2017-10-11 09:39:34 | NULL       | NULL       |
|  3 | Regular  | M    | 2017-10-11 09:39:37 | NULL       | NULL       |
|  4 | Regular  | xxl  | 2017-10-11 13:03:52 | NULL       | NULL       |
|  5 | Regular  | l    | 2017-10-11 13:03:59 | NULL       | NULL       |
|  6 | Regular  | xm   | 2017-10-11 13:04:03 | NULL       | NULL       |
|  7 | Small    | em   | 2017-10-11 13:05:04 | NULL       | NULL       |
|  8 | standard | em   | 2017-10-13 07:16:50 | NULL       | NULL       |

In this table i have some sample data. I need to group the size based on category For.eg

Regular = [s,xs,M,l,xm]
standard = [em]
small = [em]

How to achieve this on my php controller function

public function sizeFetch(Request $request){
        $cat_id = $request->id;
        $size_id = SizeCategory::where('category_id',$cat_id)->pluck('size_id');
    $size_details = SizeChart::whereIn('id',$size_id)->get();

        return $size_details;
    }

Now this function return like this

[
{
id: 1,
category: "Regular",
size: "S",
created_at: "2017-10-11 09:35:14",
updated_at: null,
deleted_at: null
},
{
id: 2,
category: "Regular",
size: "XS",
created_at: "2017-10-11 09:39:34",
updated_at: null,
deleted_at: null
},
{
id: 3,
category: "Regular",
size: "M",
created_at: "2017-10-11 09:39:37",
updated_at: null,
deleted_at: null
},
{
id: 7,
category: "Small",
size: "em",
created_at: "2017-10-11 13:05:04",
updated_at: null,
deleted_at: null
}
]

Please help me to resolve this

like image 421
Karthiga Avatar asked Nov 19 '25 12:11

Karthiga


1 Answers

It's probably easier if you do the grouping after you get results. The problem with grouping within the query is that it doesn't really do what you'd expect. (GROUP BY in SQL probably should have been called AGGREGATE BY instead)

public function sizeFetch(Request $request){
    $cat_id = $request->id;
    $size_id = SizeCategory::where('category_id',$cat_id)->pluck('size_id');
    $size_details = SizeChart::whereIn('id',$size_id)
        ->get()->groupBy("category") //Group by category
             ->map(function ($group) {
                   return $group->pluck("size"); //Pluck size from each category member
             });

    return $size_details;
}
like image 110
apokryfos Avatar answered Nov 21 '25 02:11

apokryfos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!