Laravel query builder binding parameters more than once

Viewed 25614

I'm trying to bind the same value to some parameter in a raw query (Laravel 5.2)

//this is a non practical example ,only for clarify the question

DB::table('users as u')
->select('id')
->whereRaw('u.id > ? or u.id < ? or u.id = ?',[$id, $id, $id])
->first();

is there any way to bind the same parameters at once(prevent duplicating values in [$id, $id, $id])?

2 Answers

As @tremby has answered, You can use

DB::table('users as u')
  ->select('id')
  ->whereRaw('u.id > :id or u.id < :id or u.id = :id',['id'=>2])
  ->first();

to use named binding.

Additionally, You have to set PDO::ATTR_EMULATE_PREPARES => true in config/database.php in order to get rid of the Invalid parameter number exception, like:

config/database.php

'mysql' => [
  'driver'    => 'mysql',
  ...
  'options' => [
    PDO::ATTR_EMULATE_PREPARES => true,
  ],
],

Reference: https://github.com/laravel/framework/issues/12715#issuecomment-197013236

Related