Database
Laravel – Getting multiple rows in just one row separated by commas
Let’s get initial result to create a scenario to make you understand what we are going to do here. Based on a query below, you will get result of bill id along with associated payment type used like, cash, card or esewa.
$result = PaymentType::leftJoin('bills', 'bills.id', '=', 'payment_types.id')->get(); dd($result);
Here is the result. As you can see we got 3 bill ids along with payment types. But what we are trying to achieve is to merge those 3 rows in single row as bill_id = 1.
bill_id | payment_type |
---|---|
1 | cash |
1 | card |
1 | e-sewa |
$result = PaymentType::leftJoin('bills', 'bills.id', '=', 'payment_types.id')->select([ DB::raw('bills.id as bill_id'), DB::raw('group_concat(payment_types.name) as payment_type_names'), ]) ->groupBy('bills.id') ->get(); dd($result);
Here is the result as expected.
bill_id | payment_type_names |
---|---|
1 | cash, card, e-sewa |
Well, this will help a lot to reduce your unnecessary loops. I hope this was helpful. Let me know if there is any problem.
Thanks
Santosh Maharjan
0
Tags :