How to get the query builder raw SQL in Laravel

Sometimes you want to know the exact Laravel raw query , the exact SQL output string executed under the hood, for a given instance of the database query builder.

Let’s say you have this query:


You can get the raw SQL query string that the query builder above will generate in at least two ways:

  1. use the toSql() function
  2. use the enableQueryLog() function

Solution 1: the toSql() function

Replace the query builder get() call with a toSql() call and echo it, like this:

echo DB::table('users')->toSql();

Laravel will return:

select * from users

Solution 2: the enableQueryLog() function

Enable the query log, prepending the query builder call with this line:


Then, add a line like this AFTER the query builder call:


Laravel will return:

array(1) {
  array(3) {
    string(21) "select * from "users""
    array(0) {}
    string(4) "0.71"

Leave a Reply

Your email address will not be published. Required fields are marked *