Level 13
You can use DB::select($query)
Be carefull with your query when using user provided parameters. Those will not be escaped.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have some complex query which I need for pagination:
SELECT
( SELECT COUNT(*)
FROM table
WHERE ...
) AS column1,
SUM(CASE WHEN ... END) AS column2,
column3, column4, column5
FROM table T
WHERE ...
GROUP BY ...
And I need to paginate the result. But if I use it with eloquent or query builder RAW it adds antother from at the bottom:
$data = Model::selectRaw('
SELECT
( SELECT COUNT(*)
FROM table
WHERE ...
) AS column1,
SUM(CASE WHEN ... END) AS column2,
column3, column4, column5
FROM table T
WHERE ...
GROUP BY ...
')
->paginate('100');
when using toSql it adds to the very bottom another from, so it basically does the exact above query just with extra:
SELECT
( SELECT COUNT(*)
FROM table
WHERE ...
) AS column1,
SUM(CASE WHEN ... END) AS column2,
column3, column4, column5
FROM table T
WHERE ...
GROUP BY ...
FROM table
How can I remove it and still make it work with pagination?
Please or to participate in this conversation.