I\'m trying to debug some SQL queries that I\'m doing in a testing suite. Using the following debugging code:
\\Log::debug(User::first()->jobs()->toSql
In addition to @wader's answer, a 'macroable' way to get the raw SQL query with the bindings.
Add below macro function in AppServiceProvider boot() method.
\Illuminate\Database\Query\Builder::macro('toRawSql', function(){
return array_reduce($this->getBindings(), function($sql, $binding){
return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
}, $this->toSql());
});
Add an alias to the Eloquent Builder.
\Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
return ($this->getQuery()->toRawSql());
});
Then debug as usual.
\Log::debug(User::first()->jobs()->toRawSql());
Note: from Laravel 5.1 to 5.3, Since Eloquent Builder doesn't make use of the
Macroabletrait, cannot addtoRawSqlan alias to the Eloquent Builder on the fly. Follow the below example to achieve the same.
E.g. Eloquent Builder (Laravel 5.1 - 5.3)
\Log::debug(User::first()->jobs()->getQuery()->toRawSql());