How To Execute 'LIKE' Raw Query with Binding? Hi,
This works
DB::select("SELECT * FROM `users` WHERE `name` = :name", ['name' => $request->name]);
But this returns empty result
DB::select("SELECT * FROM `users` WHERE `name` LIKE '%:name%'", ['name' => $request->name]);
What is wrong with second query?
Thanks!
try this
DB::select("SELECT * FROM `users` WHERE `name` LIKE '%' . $request->name . '%'");
or
DB::select("SELECT * FROM `users` WHERE `name` LIKE '%$request->name%'");
@rin4ik
This works but prone to attack because we are directly using whats provided on request.
The reason I am trying to run with named binding is to leverage the data sanitation provided by Laravel out of the box.
https://laravel.com/docs/5.6/database#running-queries
Also I don't know the parameter beforehand. Have to check based on what user had provided on search form.
Any other suggestion?
Try this one
DB::table('users')
->where('name', 'like', '%' . $request->name . '%')
->get();
or
DB::select("SELECT * FROM `users` WHERE `name` LIKE ':name'", ['name' => '%' . $request->name . '%']);
@Yorki
It doesn't work. However thanks for giving the variation idea. After some experiment, figured out that apostrophe is not needed (its kind of redundant).
This works
DB::select("SELECT * FROM `users` WHERE `name` LIKE :name", ['name' => '%' . $request->name . '%']);
or
DB::select("SELECT * FROM `users` WHERE `name` LIKE :name", ['name' => "%$request->name%"]);
Thanks
Please sign in or create an account to participate in this conversation.