How to Debug Sql Queries in Laravel

How to debug SQL queries in Laravel & Lumen. During development of an application, there may be times when we need to write large and complex queries. Laravel provides an awesome query builder and ORM (Eloquent) to do this task effortlessly. But sometimes we would like to see the actual SQL being generated.

In this tutorial, we are going to learn different ways to debug SQL queries in Laravel.

How to debug sql queries in laravel & lumen

How to debug SQL queries in laravel & lumen

How to Debug SQL Queries in Laravel & Lumen

For better understanding, let’s take an eloquent query and then we try to generate the raw SQL query from that.

To generate the raw SQL query, we can simply use Laravel toSql() method. Let’s try it and see the result.

Output –

Laravel toSql() method is good for seeing the raw SQL query. But what about query bindings. How do we see the query bindings ? Let’s check the Laravel getBindings() method.

Output –

Enable and Print Query Log

In Laravel, query log is disabled by default we can enable it and print the query log.

Output –

Register Event Listener

Another option is to listen for query events on the DB object.

Using DB::listen we can print SQL query, parameter bindings and the time taken by the query to run.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.