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

filipbaginski's avatar

Query error

Hi everyone,

I have an error in query and I'm not able to see what I did wrong:

    {
        return $request->withOrdering($request->withFilters(
            $query
                ->select(DB::raw('users.id as 'id', users.name as 'name', sum(products.price) as 'total''))
                ->join('orders', 'users.id', '=', 'orders.user_id')
                ->join('products', 'products.id', '=', 'orders.product_id')
                ->groupBy('users.id')
        ));
    }'​ ```

It give me an error: syntax error, unexpected identifier "id", expecting ")"
0 likes
7 replies
amjadAH's avatar

Simply because you are writing single quotes inside single quotes, try to remove the inside single quotes, or by skipping them using the backslash,

return $request->withOrdering($request->withFilters(
    $query
        ->select(DB::raw('users.id as id, users.name as name, sum(products.price) as total'))
        ->join('orders', 'users.id', '=', 'orders.user_id')
        ->join('products', 'products.id', '=', 'orders.product_id')
        ->groupBy('users.id')
));
1 like
filipbaginski's avatar

@amjad-ah

Also this query gives me the same error:

->from(DB::raw('
                            (select
                            users.id 'id',
                            users.name 'name',
                            sum(product.price) 'total',
                            users.deleted_at
                            from users
                            inner join orders on users.id = orders.user_id
                            inner join products on products.id = orders.product_id
                            group by users.id) users
                        '))
                      ->select('id', 'name', 'total', 'deleted_at')
amjadAH's avatar
amjadAH
Best Answer
Level 3

@filipbaginski

just like we did before,

->from(DB::raw('
                            (select
                            users.id id,
                            users.name name,
                            sum(product.price) total,
                            users.deleted_at
                            from users
                            inner join orders on users.id = orders.user_id
                            inner join products on products.id = orders.product_id
                            group by users.id) users
                        '))
                      ->select('id', 'name', 'total', 'deleted_at')
1 like
filipbaginski's avatar

@amjad-ah We :-) Thanks again. Works! The last problem with this query I have is how by default order column 'total' e.g. asc

filipbaginski's avatar

Fixed:

->select('id', 'name', 'total', 'deleted_at')
->orderBy('total', 'desc')

Please or to participate in this conversation.