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.
Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With