How can I get the raw query string from Laravel's query builder BEFORE executing the query?
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() );
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());}
Piggy back off andi79h's answer. The function works well, except it's assuming binding would not have any quotes that could break the query.
I added "addslashes" to $bindings to make it a bit safer. Although, ideally, it should be run through mysqli_real_escape_string() if you have an active connection to work with.https://www.php.net/manual/en/mysqli.real-escape-string.php
/** * 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) { $binding = addslashes($binding); return is_numeric($binding) ? $binding : "'{$binding}'"; })->toArray());}