How to get the Raw SQL Query from the Laravel Query

867 views 5 months ago 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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]