1

This seems very easy query but can't translate it into laravel query. I have table orders there are two columns total_usd and total_gbp. I want to sum each column to get total of usd and total of gbp on the page.

This query is working in phpmyadmin and I got correct result

SELECT sum(order_total_usd) as usd, sum(order_total_gbp) as gbp FROM `orders`

In laravel I've tried this

$sumOrders = Order::select('sum(order_total_gbp) as gbp, sum(order_total_usd) as usd');

when I dd($sumOrders) I've one really huge output which almost cause browser to freeze. Where is my mistake here?

3 Answers 3

1

You can try something like this

$sumOrders = Order::select( \DB::raw("sum(order_total_gbp) as gbp"),  \DB::raw("sum(order_total_usd) as usd"))->get();
Sign up to request clarification or add additional context in comments.

5 Comments

Okay, thanks. Now when I dd($sumOrders['gbp']) in order to access the sum of gdp I've got Undefined index: gdp.
You have to get like $sumOrders->gdp
When I dd($sumOrders->gbp) I've got ErrorException: Undefined property: Illuminate\Database\Eloquent\Builder::$gbp. When I dd($sumOrders) I've got one relatively long array and inside I can see array(2) { ["gbp"]=> float(0.43829558) ["usd"]=> float(27) }
Okay got it to work. I've changed ->get() with ->first() at the end and now is working. Thanks
@Ivan Glad I could help! :) –
0

You can use selectRaw

$sumOrders = Order::selectRaw('sum(order_total_gbp) as gbp, sum(order_total_usd) as usd');

1 Comment

Thanks but this return again ErrorException: Undefined property: Illuminate\Database\Eloquent\Builder::$gbp
0

Except for one missed word, your code is OK. Add "Raw" after "select" as shown:

$sumOrders = 
Order::selectRaw(
    'sum(order_total_gbp) as gbp, 
    sum(order_total_usd) as usd'
);

Just replace "Order::select(...)" with Order::selectRaw(...).

Have a great day!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.