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

Reinis.lucis's avatar

Make calculations in Elequent Query

Hey! 👋🏼

I have an Eloquent query where I need to add calculations in it to sort by. In this case, I need to add successful_requests * 100 / total_requests as an additional attribute, is there any way how that can be done in Eloquent and not using DB::raw? I know that withCount runs as a sub-query, that's why those values like total_requests are not accessible

        $query = Domain::query()
            ->withCount(
                [
                    'formTestRequests',
                    'formTestResults as total_requests',
                    'formTestResults as successful_requests' => function ($query) {
                        $query->where('status', '=', 'success');
                    },
                ]
            )
0 likes
1 reply
Reinis.lucis's avatar
Reinis.lucis
OP
Best Answer
Level 1

In this case I was able to use

->orderByRaw('(successful_requests * 100 / total_requests) desc');

Please or to participate in this conversation.