Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I get the query builder to output its raw SQL query as a string?

Given the accompanying code:

DB::table('users')->get();

I need to get the raw SQL inquiry string that the information base question developer above will create. In this model, it would be SELECT * FROM users.

How would I do this?
by

4 Answers

espadacoder11
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 think the most recent queries will be at the bottom of the array.

You will get something like :

array(1) {
[0]=>
array(3) {
["query"]=>
string(21) "select * from "users""
["bindings"]=>
array(0) {
}
["time"]=>
string(4) "0.92"
}
}
RoliMishra
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.
akshay1995
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.
sandhya6gczb
You can listen to the 'illuminate.query' event. Before the query add the following event listener:

Event::listen('illuminate.query', function($query, $params, $time, $conn)
{
dd(array($query, $params, $time, $conn));
});

DB::table('users')->get();

This will print out something like:

array(4) {
[0]=>
string(21) "select * from "users""
[1]=>
array(0) {
}
[2]=>
string(4) "0.94"
[3]=>
string(6) "sqlite"
}

Login / Signup to Answer the Question.