Manish
Manish

Reputation: 1972

Eloquent Raw where query using like condition

I am using this Eloquent raw query to fetch some search results combining both caption and tags column. my code goes like this

$term="Test";
$clips=  \Clip::whereRaw("caption like '%?%' OR tags like '%?%' ", array($term,$term))->get();
dd($clips);

but using this I am not able to get results as the dump shows no results, where as using below code I am able to get results:

$term="Test";
$clips=  \Clip::whereRaw("caption like '%$term%' OR tags like '%$term%' ")->get();
dd($clips);

and dump shows all 5 results which are expected. What am I doing wrong in first case.

Upvotes: 10

Views: 40630

Answers (1)

Bram
Bram

Reputation: 4532

If you use prepared statements, you should use a ? and nothing else. If you're adding quotes yourself, you should not be using prepared statements. So let the prepared statement take care of the quotes and add the %-sign to the variable you are inserting into the prepared statement.

$term="Test";
$clips=  \Clip::whereRaw("caption like ? OR tags like ? ", array('%'.$term.'%','%'.$term.'%'))->get();
dd($clips);

By the way, you could also do this without a raw where..

$term="Test";
$clips=\Clip::where("caption","like","%".$term."%")->orWhere("tags","like","%".$term."%")->get();
dd($clips);

... and personally I would even prefer to use a scope for these kind of things.

Upvotes: 23

Related Questions