Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 320
meiryo Avatar asked Aug 14 '13 15:08

meiryo


People also ask

What is raw SQL query?

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.

How do I get SQL laravel eloquent?

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.


2 Answers

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.)

like image 20
jfortunato Avatar answered Sep 21 '22 17:09

jfortunato


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.

like image 148
Steven Mercatante Avatar answered Sep 20 '22 17:09

Steven Mercatante