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

anand_aks's avatar

Performance btw Laravel Query Builder and SQL

I have a DB view called 'barcode_filter'

Calling a select query using Query Builder

    $menu = DB::table('barcode_filter')->select('short_descip','short_descip1', 'retail1', 'barcode','dept_code','tax_perc', 'tax_flag','availability','qty_check','recipe_item_code','recipe_qty','preparation_time','discount_amt','discount_flag')
                   ->where('company_code',2)
                   ->where('branch_code',$branchCode)
                   ->where('dept_code',$departmentCode)
                   ->where('online',1)
                   ->where('avail',1)
                   ->get();

It took 4.17s to return the result

Then I tried SQL

   $menu = DB::select('SELECT short_descip,short_descip1,retail1,barcode,dept_code,tax_perc,tax_flag, qty_check,recipe_item_code,recipe_qty,preparation_time,discount_amt,discount_flag
 FROM kloudc5_demo.barcode_filter where company_code = 2 and branch_code = '.$branchCode.' and dept_code = '.$departmentCode.' and online = 1 and avail = 1');



it only took 637ms to return the result

Why this much difference. Used ajax for both queries.

0 likes
9 replies
automica's avatar

The difference in performance sounds more like an issue with your environment than the query.

What are you running your development environment on?

automica's avatar

I’ve seen various reports with slow DB access times on windows since being on laracasts. My suggestion would be to set up either laravel sail or homestead and use that.

IIRC it can be caused by local DNS. Are you accessing your DB by localhost or 127.0.0.1?

anand_aks's avatar

Yes by localhost. I have used laravel query builder for all other functions and which are working fine with no problem. Only reading from the view is slow. So i am now using sql query when reading from view.

Tray2's avatar

The second time you run a query it's usually faster since it's been parsed and cached by the database.

anand_aks's avatar

No i tried each query multiple times. It is not a problem with cache

sr57's avatar

Hi @anand_aks

Light differences are normal (more layers to convert in raw sql at the end) but so much is questionable.

-1 is to compare the sql generated and see the differences. Use dd or dump to see raw sql by query builder

https://laravel.com/docs/8.x/queries#debugging

-2 if difference is not obvious , run the 2 sql directly to reproduce or not the pb.

-3.1 use explain if still difference

-3.2 debug framework/php if no difference

-3.3 if you can try also with mysql and postgresl

Please or to participate in this conversation.