Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 741
Manish Avatar asked Feb 22 '14 10:02

Manish


People also ask

How do you use like in eloquent?

Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();

What is DB :: Raw?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.

What is the difference between query builder and eloquent?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.


1 Answers

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.

like image 138
Bram Avatar answered Dec 05 '22 11:12

Bram