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());
The SQL that prints out is:
`select * from `jobs` where `jobs`.`deleted_at` is null and `jobs`.`managed_by_id` = ? and `jobs`.`managed_by_id` is not null`
What is that question mark doing there? I've tested the query, and it works as expected. Is it because i'm selecting that first() user that this is happening?
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.
You have to use the dd() method after toSql() to print the query in your controller file. Dump() method will print the query information but it does not stop the execution of the script. DB::enableQueryLog(); and dd(DB::getQueryLog()); are the methods which are used to print queries in laravel.
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.
Laravel uses Prepared Statements. They're a way of writing an SQL statement without dropping variables directly into the SQL string. The ?
you see are placeholders or bindings for the information which will later be substituted and automatically sanitised by PDO. See the PHP docs for more information on prepared statements http://php.net/manual/en/pdo.prepared-statements.php
To view the data that will be substituted into the query string you can call the getBindings()
function on the query as below.
$query = User::first()->jobs();
dd($query->toSql(), $query->getBindings());
The array of bindings get substituted in the same order the ?
appear in the SQL statement.
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