laravel

Add 2 array values in Laravel


I a, new learner and working on home project. I stuck to to get additions of 2 array values . The array values are as follows, Thanks for your help.. Thanks u

Array 1

array:1 [▼
    0 => array:3 [▼
        "totalbmilk" => "168.00"
        "totala2milk" => "0.00"
        "totaljmilk" => "390.00"
    ]
]

Array 2

array:1 [▼
    0 => array:3 [▼
        "totalbmilk" => "8.00"
        "totala2milk" => "5.50"
        "totaljmilk" => "2.50"
    ]
]

Expecting

Controller file

$milksalefordairy = Dairymilksale::selectraw('
        SUM(buffalomilk) as "totalbmilk",
        SUM(a2milk) as "totala2milk",
        SUM(jerseymilk) as "totaljmilk"
    ')
    ->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
    ->get()
    ->toArray();
    
$milksaleforcustomer = Customermilksale::selectraw('
        SUM(buffalomilk) as "totalbmilk", 
        SUM(a2milk) as "totala2milk",
        SUM(jerseymilk) as "totaljmilk"
    ')
    ->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
    ->get()
    ->toArray();

Solution

  • You could use collection methods.

    $milksalefordairy = Dairymilksale::selectraw('
            SUM(buffalomilk) as "totalbmilk",
            SUM(a2milk) as "totala2milk",
            SUM(jerseymilk) as "totaljmilk"
        ')
        ->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
        ->get()
        ->toArray();
        
    $milksaleforcustomer = Customermilksale::selectraw('
            SUM(buffalomilk) as "totalbmilk", 
            SUM(a2milk) as "totala2milk",
            SUM(jerseymilk) as "totaljmilk"
        ')
        ->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
        ->get()
        ->toArray();
    
    $collection = collect([...$milksalefordairy, ...$milksaleforcustomer]);
    
    echo $collection->sum('totalbmilk');
    echo $collection->sum('totala2milk');
    echo $collection->sum('totaljmilk');