How to get the Raw SQL Query from the Laravel Query
source link: https://www.laravelcode.com/post/how-to-get-the-raw-sql-query-from-the-laravel-query
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to get the Raw SQL Query from the Laravel Query
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
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]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK