Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the raw query string from Laravel's query builder BEFORE executing the query?

I have a complex query created by a few conditions, and I would like to get the final SQL query from the builder object is about to execute. Can I do that?

like image 525
Matteo Riva Avatar asked Nov 18 '13 10:11

Matteo Riva


People also ask

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

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.

How do you find an eloquent query?

If you write your query in Tinkerwell anyway, you can highlight the Eloquent query and press Cmd+Shift+R (or Ctrl+Shift+R if you are on Windows) and Tinkerwell profiles the query directly in the editor. You see all executed queries, the time that the query run, the memory consumption and even the peak for your memory.

What is a raw query in SQL?

On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.


2 Answers

You can get it doing:

$query = DB::table('brands')                 ->join('products','a','=','c')                 ->whereNull('whatever');  echo $query->toSql(); 

But Laravel will not show you parameters in your query, because they are bound after preparation of the query.

So you can also do:

print_r( $query->getBindings() ); 
like image 180
Antonio Carlos Ribeiro Avatar answered Sep 21 '22 07:09

Antonio Carlos Ribeiro


For debugging this might come quite handy as it returns the SQL with the bindings, so you can instantly put it into the database console.

/**  * Combines SQL and its bindings  *  * @param \Eloquent $query  * @return string  */ public static function getEloquentSqlWithBindings($query) {     return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {         return is_numeric($binding) ? $binding : "'{$binding}'";     })->toArray()); } 
like image 43
andi79h Avatar answered Sep 20 '22 07:09

andi79h