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

adnan483's avatar

Better solution for SQL query

I have these two queries

$na = DB::select('select n.*,u.name from nalog2019s n,users u where n.user_id=u.id order by n.id desc');
$voo = DB::select('select * from vrsta_otvora2019s');

and in view in table

@foreach($voo as $vo)
        @if($na->id == $vo->nalog_id)
          <li>{{ $vo->naziv }} : <strong>{{$vo->kolicina}}</strong></li>
        @endif
@endforeach

this all works but it's too slow, how can I improve this to get all in one query?

0 likes
4 replies
bobbybouwmann's avatar

Well, the queries look pretty solid to me and they should be really fast. You can, for example, install the laravel-debugbar and see the performance per query. I assure you that the query is fast.

It will be slow if you have a lot of results and start looping over them. How many results do you get back?

adnan483's avatar

That is main problem, I'm getting now 1800+ but that number always goes over 2200+

shez1983's avatar

it seems to be theres a relationship between voo/na.. so you can utilise laravels relationship to only SELECT rows which are matching - you are getting all the voo and na and then in php disregarding the ones that dont have a matching comparison.

the other thing is ofcourse pagination - you should only get 15 or so results at a time..

third solution would be caching.

you can do all three in combination with each other

adnan483's avatar

I can do this without problem with Eloquent but on this way, I don't know how to speed up this app

Please or to participate in this conversation.