Abey
Abey

Reputation: 1428

Unable to bind parameters in Laravel raw query

I'm trying to bind vars to my raw query,

$query = "SELECT 1 AS rank, 'CATEGORY' AS type, category_id AS id, name AS name
          FROM category_translations
          JOIN categories ON categories.id = category_translations.category_id
          WHERE name LIKE '%?%'";

$results = DB::select($query, ['ger']);

But I am unable to do so. I have tried by binding named params, and also using DB::raw inside DB::select without any success.

What am I doing wrong here?

Upvotes: 1

Views: 789

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

You need to add the %'s to the bind value and not in the query (unless you concat() the values)...

$query = "SELECT 1 AS rank, 'CATEGORY' AS type, category_id AS id, name AS name
          FROM category_translations
          JOIN categories ON categories.id = category_translations.category_id
          WHERE name LIKE ?";

$results = DB::select($query, ['%ger%']);

Upvotes: 2

Jignesh Joisar
Jignesh Joisar

Reputation: 15115

try to used like that

$query = "SELECT 1 AS rank, 'CATEGORY' AS type, category_id AS id, name AS name
          FROM category_translations
          JOIN categories ON categories.id = category_translations.category_id
          WHERE name LIKE '% :nameSearch %'";

$results = DB::select(DB::raw($query), ['nameSearch' => 'ger']);

second way used like that

$searchText = "ger";
$results = DB::select(DB::raw($query), ['nameSearch' => "%".$searchText."%"]);

Upvotes: 1

Related Questions