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:
DB::table('users')->get();
You can get the raw SQL query string that the query builder above will generate in at least two ways:
- use the toSql() function
- 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:
DB::enableQueryLog();
Then, add a line like this AFTER the query builder call:
dd(DB::getQueryLog());
Laravel will return:
array(1) { [0]=> array(3) { ["query"]=> string(21) "select * from "users"" ["bindings"]=> array(0) {} ["time"]=> string(4) "0.71" } }