Home » Laravel » How to Get Raw SQL Query in Laravel

How to Get Raw SQL Query in Laravel

Laravel has an excellent query builder called Eloquent. It supporting complicated where combinations, grouping, ordering, joins, a lot of types relation and other things. So you can cover 90% of your requirements using Eloquent and not to write raw SQL code.

But when you have troubles with Eloquent queries you may want show raw SQL query generated by it. In this article we will explain how to get raw SQL query in Laravel.

How to Get Raw SQL Query in Laravel

1. Using dd()

The simplest way to debug Eloquent queries – use toSql() method instead of get(), paginate(), first() or any equivalent method. For example:

dd(Article::query()->toSql());

Let’s have a look at a different situation. Imagine that you have database query, that will extract articles with comments from the database:

$articles = Article::query() ->with([ "comments" => function (Relation $query) { $query->limit(2); }, ]) ->withCount("comments") ->paginate(10);

This code will execute a few queries to the database, so you can’t debug it using toSql() method. If you want to debug this query you should enable SQL debugging first. Add this line before code that you want to debug:

DB::enableQueryLog(true);

Then, get query log after the code execution using this code:

dd(DB::getQueryLog());

It will look like this:

You can debug any query using this way.

2. Using Telescope

The laravel/telescope package can help you to debug not only HTTP requests but also database queries related to them. If the package is not installed, you can install it using following command:

composer require laravel/telescope --dev

After this, run migrations and the install command:

php artisan telescope:install php artisan migrate

Open telescope in your browser using http://application_domain/telescope. Then open any request that you want to debug, and open Queries tab:

Here, you can click on eye button and view details for each SQL query:

That’s it.

Wrapping Up

In this article we have explained how to get raw SQL query in Laravel using dd() instruction or the telescope package.

Your Reaction

Leave a Comment

Exit mobile version