2

I running this code :

$id = 1;
$email = 'email@gmail.com';

$user = DB::table('users')->where([
  ['id', '=', $id],
  ['email', '=', $email]
])->toSql();
dd($user);

But query builder print is :

select * from `users` where (`id` = ? and `email` = ?)

Why not print is:

select * from `users` where (`id` = 1 and `email` = email@gmail.com)

3 Answers3

1

the query builder inserts the characters in place of the values to protect you from the sql injections, then he himself will set the values to you as needed, and you will get the finished result, and the fact that you are displayed on the screen is simply viewing the query queries

  • it does not need to print it to you on the screen, it's a special security mechanism, it seems to me that you do not need to see this in the code, it's enough to keep some points in your head, but to display the variables separately, for example, in an array – Дмитрий Смирнов Feb 25 '18 at 16:28
0

That's how toSql() method works. It just shows you prepared query but doesn't execute it.

To execute the query, do use get(), find(), first() or similar method:

$user = DB::table('users')->where([
    ['id', '=', $id],
    ['email', '=', $email]
])->first();
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • I know method `get()` , `find()`, `first()`, but my question is query builder not print `select * from \`users\` where (\`id\` = 1 and \`email\` = email@gmail.com)` instead of `select * from \`users\` where (\`id\` = ? and \`email\` = ?)` –  Feb 25 '18 at 16:17
0

Query Builder inserts the characters in place of the values to protect you from the SQL Injections.I believe @Дмитрий-Смирнов answered your query well.

Rather then using raw SQL use model directly you may cut-down your line of code using the below code:

$id = 1;
$email = 'email@gmail.com';

$user = User::where('id',$id)
            ->where('email',$email)
            ->get();
dd($user);