Database
Laravel – Getting multiple rows in just one row separated by commas

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_idpayment_type
1cash
1card
1e-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_idpayment_type_names
1cash, 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

Leave a Reply