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

AbdallahSabri's avatar

How to make this query in Eloquent

I have this query, it is working on oracle DB, How can I convert it to eloquent equivalent?

select     count(v.ID), v.SITE_NAME, to_char(v.REGISTRY_DATE,'yyyy')
from       abc.vehicles_v v 
where     to_number(to_char(v.REGISTRY_DATE,'yyyy')) > 2012
and          v.LAST_CANCEL_ID is null
group by  v.SITE_NAME,to_char(v.REGISTRY_DATE,'yyyy')
order by 2
0 likes
4 replies
kossa's avatar

Note sure but I think you can use :

DB::raw("
select     count(v.ID), v.SITE_NAME, to_char(v.REGISTRY_DATE,'yyyy')
from       abc.vehicles_v v 
where     to_number(to_char(v.REGISTRY_DATE,'yyyy')) > 2012
and          v.LAST_CANCEL_ID is null
group by  v.SITE_NAME,to_char(v.REGISTRY_DATE,'yyyy')
order by 2
");
mattsplat's avatar

This might get you closer

DB::table('vehicles_v as v')
    ->select(DB:raw('COUNT(v.ID)'), v.SITE_NAME, DB::raw('YEAR(v.REGISTRY_DATE)') )
    ->where(DB::raw('YEAR(v.REGISTRY_DATE)'), '>', 2012)
    ->whereNull('v.LAST_CANCEL_ID)
    ->groupBY(v.SITE_NAME, DB(DB::raw('YEAR(v.REGISTRY_DATE)'))
    ->orderBy(2)
    ->get()
AbdallahSabri's avatar
AbdallahSabri
OP
Best Answer
Level 1

I solved it like this

$query = "select     count(v.ID), v.SITE_NAME, to_char(v.REGISTRY_DATE,'yyyy')
               from       abc.vehicles_v v 
               where     to_number(to_char(v.REGISTRY_DATE,'yyyy')) > 2012
               and          v.LAST_CANCEL_ID is null
               group by  v.SITE_NAME,to_char(v.REGISTRY_DATE,'yyyy')
               order by 2";

$data   =   DB::select($query);
1 like

Please or to participate in this conversation.