How can i get mysql
query of a laravel
query
Convert:
App\User::where('balance','>',0)->where(...)->get();
To:
SELECT * FROM users WHERE `balance`>0 and ...
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.
DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. Since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.
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.
use toSql()
method of laravel to get the query to be executed like
App\User::where('balance','>',0)->where(...)->toSql();
But Laravel will not show you parameters in your query, because they are bound after preparation of the query. To get the bind parameters, use this
$query=App\User::where('balance','>',0)->where(...); print_r($query->getBindings() );
enable the query log as DB::enableQueryLog()
and then output to the screen the last queries ran you can use this,
dd(DB::getQueryLog());
you can add this function to your helpers
function getRealQuery($query, $dumpIt = false) { $params = array_map(function ($item) { return "'{$item}'"; }, $query->getBindings()); $result = str_replace_array('\?', $params, $query->toSql()); if ($dumpIt) { dd($result); } return $result; }
and use like this:
getRealQuery(App\User::where('balance','>',0)->where(...),true)
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