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

Crazylife's avatar

How can i write mySQL query in laravel controller?

I have a query look like this

select t.prod_id, t.datetime,b.branch_id
from A t
inner join (
    select prod_id, max(datetime) as MaxDate
    from A
    group by prod_id
) tm on t.prod_id = tm.prod_id and t.datetime = tm.MaxDate
inner join B b on b.prod_id = t.prod_id
inner join C c on b.prod_id = c.prod_id

I wrote in my controller

DB::select("select t.prod_id, t.datetime,b.branch_id
from A t
inner join (
    select prod_id, max(datetime) as MaxDate
    from A
    group by prod_id
) tm on t.prod_id = tm.prod_id and t.datetime = tm.MaxDate
inner join B b on b.prod_id = t.prod_id
inner join C c on b.prod_id = c.prod_id
 ");

It will caused infinity looping. Is this the correct way to write in this format?

0 likes
2 replies
Crazylife's avatar

@tisuchi May i know, if using DB:: select, e.g.

$value = DB::select("...")

Can i directly pass the value to view without looping?

Please or to participate in this conversation.