Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 Combining two collections

Tags:

php

mysql

laravel

So I Have two collections, sales and costs.

Now I need them to combine into one collection for my foreach condition (I'm not sure if I can use two collections in one foreach)

RAW Queries:

//Raw MySQL Queries for Sales
$total_sales = DB::raw('SUM(receipts.total) as totalSales');
$year_receipt_created = DB::raw('YEAR(receipts.created_at) as year');

//Raw MyQSL Queries for Cost of Goods Sold
$total_cost = DB::raw('(SUM(qty * cost)) as totalCost');
$year_sold = DB::raw('YEAR(created_at) as year');

Here's my query for these two collections:

$sales = DB::table('receipts')
            ->where('status', 'served')
            ->where('mode', 'restaurant')
            ->select($total_sales, $year_receipt_created)
            ->groupBy('year')
            ->get();

$costs = DB::table('orders')
            ->where('status', 'served')
            ->select($total_cost, $year_sold)
            ->groupBy('year')
            ->get();

Things I've tried testing: Converting the collections into array and tried merging them but I seem to have problems.

I reverted it because I don't know if it's the best way or not. Please let me know what's the best way.

UPDATE: Here's the output for those two queries, hope it helps:

Sales

{
    totalSales: "960.00",
    year: 2017
}

Costs

{
    totalCost: "792.00",
    year: 2017
}

What I tried: (It says it cannot find totalCost)

//Combining TWO collections into ONE Array
$gross_profit = array();
foreach (array_merge($sales, $costs) as $data) 
{
    $keys = array('total_sales', 'total_cost', '$year');
    $values = array($data->totalSales, $data->totalCost, $data->year);
    $gross_profit[$data] = array_combine($keys, $values);
}

**SOLVED: ** I used collection merge (didn't knew there was such a thing)

The syntax I used is, $result = $sales->merge($costs).

Here's the result:

{
    totalSales: "960.00",
    year: 2017
},
{
    totalCost: "792.00",
    year: 2017
}

Answered by: Sagar Gautam

like image 841
Jan Ariel San Jose Avatar asked Mar 08 '23 09:03

Jan Ariel San Jose


1 Answers

Use collection merge() function like

$result = $sales->merge($costs);

You can see docs https://laravel.com/docs/5.4/collections#method-merge

like image 175
Sagar Gautam Avatar answered Mar 10 '23 22:03

Sagar Gautam