How Do I Get the Query Builder to Output Its Raw SQL Query as a String?
Use the toSql()
method on a QueryBuilder
instance.
DB::table('users')->toSql()
would return:
select * from `users`
This is easier than wiring up an event listener, and also lets you check what the query will actually look like at any point while you're building it.
Note: This method works for query builder or Eloquent, however toSql()
is used instead of first()
or get()
. You cannot run the query and also get the SQL at the same time using this method.
To output to the screen the last queries ran you can use this:
\DB::enableQueryLog(); // Enable query log
// Your Eloquent query executed by using get()
dd(\DB::getQueryLog()); // Show results of log
I believe the most recent queries will be at the bottom of the array.
You will have something like that:
array(1) {
[0]=>
array(3) {
["query"]=>
string(21) "select * from "users""
["bindings"]=>
array(0) {
}
["time"]=>
string(4) "0.92"
}
}
(Thanks to Joshua's comment below.)
DB::QueryLog()
works only after you execute the query using $builder->get()
.
If you want to get the raw query before or without executing the query, you can use the $builder->toSql()
method.
Example to get the raw SQL and to replace '?' with actual binding values:
$query = str_replace(array('?'), array('\'%s\''), $builder->toSql());
$query = vsprintf($query, $builder->getBindings());
dump($query);
$result = $builder->get();
Or you can deliberately trigger an error, for example, by using a non-existent table or column. Then you can see the generated query in the exception message.