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

somenet77's avatar

Convert into query builder ?

I have a raw query like this.

DB::select("select currency_id, sum(total) as total from (select sum(amount) as total, user_package_id, currency_id, user_packages.created_at
        from user_package_payments
        inner join user_packages
        on user_packages.id = user_package_payments.user_package_id
        group by user_package_id,currency_id
        having sum(case when (payment_type not in ('refund', 'refund_bankcharge')) then amount else 0 end) -
               sum(case when (payment_type in ('refund', 'refund_bankcharge')) then amount else 0 end) > 0)
        as x group by currency_id");

How to convert this into laravel query builder?

0 likes
7 replies
Sinnbeck's avatar

@somenet77 It sounds like you hope someone will do the work for you. If you had something like 90% of it done and was asking for the rest, or you had a specific question, we might help. But writing the whole thing from scratch is just doing your work for you.

somenet77's avatar

@Sinnbeck I want to convert this raw query into laravel query builder. This query is work 100% fine but I want to convert into laravel builder api function.

Sinnbeck's avatar

@somenet77 I know. But that is alot of manual work extracting each part. Maybe instead you should make it into a view that you can then query?

rodrigo.pedra's avatar

@somenet77 well, the query is technically already using the query builder... The DB facade you are using will even wrap the results into a collection, saving a lot of manual work then using PDO directly.

You can even move the parameters to a bindings array as the second parameter if you need them to be dynamic and want to avoid SQL injection.

And there is nothing wrong on sometimes creating a query from a SQL statement. Depending on the complexity it is easier to maintain and to understand. You can even hydrate Eloquent models from a SQL statement.

I would take @michaloravec and @sinnbeck suggestion and read the docs.

If you are struggling with some part on using a specific Query Builder feature, or it is not clear on how to do something, then we will be very glad to help.

1 like

Please or to participate in this conversation.