How to Print Sql Queries in Laravel for Debugging

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) for writing these SQL queries. But sometimes we need to print raw SQL queries for debugging.

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

How to Print Sql Queries in Laravel/Lumen for Debugging

How to Print SQL Queries in Laravel/Lumen for Debugging

How to Print SQL Queries in Laravel/Lumen for Debugging

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

To print 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 –

Subscribe Our Tutorials

Get Latest Updates on Facebook

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.

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.