Given the following code:
DB::table('users')->get();
I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users
.
How do I do this?
Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query. Raw SQL queries can return regular entity types or keyless entity types that are part of your model.
The first method to get the query of an Eloquent call is by using the toSql() method. This method returns the query without running it – good if you don't want to alter data and only get the query – but this method doesn't show the whole query if your query is more complex or if there are sub-queries.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With