Issue with raw sql queries having named bindings with multiple occurrences in Laravel

Some times we need write a really complex sql queries. Fortunately Laravel gives us such possibility:

DB::select('SELECT * FROM users WHERE id = :id', ['id' => 1]);

But some times we need to bind one and the same option, like so:

DB::select('SELECT * FROM users WHERE first_name LIKE :name OR last_name LIKE :name', ['name' => 'sample']);

Unfortunately this will not work and raises the next type error:

Illuminate\Database\QueryException
SQLSTATE[..]: Invalid parameter number (..

The right solution in this case is to duplicate named argument with different name, like:

DB::select('SELECT * FROM users WHERE first_name LIKE :fname OR last_name LIKE :lname', ['fname' => 'sample', 'lname' => 'sample']);

But, actually there is another solution, prepare raw sql query by yourself, for example:

$query = 'SELECT * FROM users WHERE first_name LIKE :name OR last_name LIKE :name';

$named_bindings = [':name' => 'sample'];

foreach ($named_bindings as $k => $v) {
    $query = str_replace($k, DB::connection()->getPdo()->quote($v), $query);
}

$result = DB::select($query);

@sources: https://laravel.com/docs/8.x/database#using-named-bindings

Leave a Reply