Mikk Mihkel Nurges
Mikk Mihkel Nurges

Reputation: 108

Laravel (5.1) query builder does not properly add bindings to a raw select statement

I'm using Laravel 5.1 and have the following simple query:

$searchTerm = 'random word';

$subQuery = DB::table('userprofile')->selectRaw("
    user_id,
    MATCH(first_name, last_name) AGAINST('?*' IN BOOLEAN MODE) AS search_score
")
->addBinding($searchTerm)
->get();

This returns nothing, but when I directly replace the quotation mark with

... AGAINST('$searchTerm*' IN BOOLEAN MODE) ...

then the results are correct. However, if I do

DB::getQueryLog();

I get

"query" => "select `user_id`, MATCH(first_name, last_name) AGAINST('?*' IN BOOLEAN MODE) AS search_score from `userprofile`"
"bindings" => array:1 [
  0 => "random word"
]

so it's as if the bindings should be added, but they're not. I have tried all variations of select, selectRaw, ->setBindings, ->addBinding($searchTerm, ['select']) etc. that have been suggested elsewhere. How can I make these bindings work?

Upvotes: 1

Views: 255

Answers (1)

Taha Paksu
Taha Paksu

Reputation: 15616

did you try replacing the whole regex like this?

$searchTerm = 'random word*';

$subQuery = DB::table('userprofile')->selectRaw("
    user_id,
    MATCH(first_name, last_name) AGAINST(? IN BOOLEAN MODE) AS search_score
")
->addBinding($searchTerm)
->get();

This way maybe the extra quotes would be not added if laravel adds them.

Upvotes: 1

Related Questions