Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Laravel's toSql() method mask ids? (column value being replaced by question mark)

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?

like image 494
Zach Smith Avatar asked Sep 03 '15 09:09

Zach Smith


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 I print a query in laravel controller?

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.

How can I see SQL 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.


1 Answers

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.

like image 116
Wader Avatar answered Oct 26 '22 22:10

Wader