How to convert query builder to raw SQL query in Laravel

Hello guys,

Sometimes, you may want to execute Laravel query builder into MySQL command line or phpMyAdmin SQL tab. You can't run Laravel query into MySQL command line. You need to convert it to raw SQL query.

In this article, I will show you two ways you can convert Laravel query to raw SQL query.

First method is using enableQueryLog() and getQueryLog() method. enableQueryLog() method will start loggin query and getQueryLog() method will catch last query.

Example:

\DB::enableQueryLog();

$users = \DB::table('users')
    ->where('id', '1')
    ->first();

dd(\DB::getQueryLog());

Or Eloquent query using model.

\DB::enableQueryLog();

$users = User::where('id', '1')
	->first();

dd(\DB::getQueryLog());

This will return array:

[
    0 => [
        "query" => "select * from `users` where `id` = ? limit 1"
        "bindings" => [
              0 => "1"
        ],
    "time" => 1.74
      ]
]

Second way is using toSql() method before using get() or first() method.

$users = \DB::table('users')
    ->where('id', '1')
    ->toSql();

dd($users);

Or using Model query.

$users = User::where('id', '1')
    ->toSql();

dd($users);

This will return raw query string.

select * from `users` where `id` = ?

So, this way you can convert Laravel query to raw SQL query.