Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ajvanho's avatar
Level 14

Raw Expressions

How to correctly write raw expressions?

Example: ´´´ $orders = DB::table("orders")->select(DB::raw(created_at as date) as stat_day, SUM (billing_totalprice) GROUP BY (created_at as date) order by stat_day));

0 likes
6 replies
bobbybouwmann's avatar

Well, you forgot your quotes here

$orders = DB::table("orders")->select(DB::raw("created_at as stat_day, SUM(billing_totalprice) GROUP BY created_at order by created_at"));

Also, your query is a bit weird. Everything points to the created_at column and you only rename them in your query but you don't do anything with it...

1 like
Ajvanho's avatar
Level 14

Something is wrong, i dd $orders, this is a resut:

+columns: array:1 [▼ 0 => Illuminate\Database\Query\Expression {#322 ▼ #value: "created_at as stat_day, SUM(billing_totalprice) GROUP BY created_at order by created_at" } ]

Ajvanho's avatar
Level 14

...and I must have DB::raw(created_at as date), beacuse i want Sum for the date, not date and time...

bobbybouwmann's avatar

You always need to call ->first() or ->get() at the end to actually perform the query.

$orders = DB::table("orders")
    ->select(DB::raw("created_at as stat_day, SUM(billing_totalprice) GROUP BY created_at order by created_at"))
    ->get();
Ajvanho's avatar
Level 14

1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'GROUP BY created_at order by created_at from orders' at line 1 (SQL: select created_at as stat_day, SUM(billing_totalprice) GROUP BY created_at order by created_at from orders)

Ajvanho's avatar
Level 14

This working for me, but i dont have result that I want.

$orders = DB::select('SELECT created_at as stat_day, SUM(billing_totalprice) from Orders GROUP BY created_at order by stat_day;');

I want Sum for one day!

0 => {#322 ▼ +"stat_day": "2020-03-16 14:44:02" +"SUM(billing_totalprice)": "150" } 1 => {#325 ▼ +"stat_day": "2020-03-18 09:07:25" +"SUM(billing_totalprice)": "147" } 2 => {#326 ▼ +"stat_day": "2020-03-18 10:00:00" +"SUM(billing_totalprice)": "50"

I will ask a subsequent question, to see if anyone can help me.

Please or to participate in this conversation.