Framework: Eloquent WHERE LIKE query escaping with '%' character behaves unexpectedly

Created on 17 Oct 2017  Â·  4Comments  Â·  Source: laravel/framework

  • Laravel Version: 5.4.36
  • PHP Version: 7.0
  • Database Driver & Version: MySQL 5.6.36

Description:

When attempting to query using eloquent with a LIKE statement, the search term gets urldecoded which causes, for example, a '%23' to resolve to another character unexpectedly.

Steps To Reproduce:

//A common use case for term would be user input from a search form:
//eg: $term = $request->input('search');
$term = '23 test';

$query = User::where('name', 'LIKE', '%' . $term . '%');

dd($query->toSql(), $query->getBindings());

The dd() will output a dump showing the binding as # test% instead of %23 test%

A quick workaround is to use $term = urlencode($term); but this seems like it shouldn't be required. I would expect to be able to search with a LIKE query + % + digits in a Database query without having to first URL encode them.

Most helpful comment

Facing the same problem today, you can do

$query = User::where('name', 'LIKE', "%$term%");
dd($query->toSql(), $query->getBindings());

// toSql() print
"select * from `Users` where `name` LIKE ?"
// getBindings() print
array:1 [â–¼
  0 => "%yourterm%"
]

This should work.

All 4 comments

Can't replicate this in 5.5.

Please upgrade to 5.5 as your version is currently not supported.

Facing the same problem today, you can do

$query = User::where('name', 'LIKE', "%$term%");
dd($query->toSql(), $query->getBindings());

// toSql() print
"select * from `Users` where `name` LIKE ?"
// getBindings() print
array:1 [â–¼
  0 => "%yourterm%"
]

This should work.

How about 2 or 3 or more LIKE?

$categories = DB::Where('name', 'like', '%' . Input::get('name') . '%')->get();

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iivanov2 picture iivanov2  Â·  3Comments

ghost picture ghost  Â·  3Comments

lzp819739483 picture lzp819739483  Â·  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  Â·  3Comments

felixsanz picture felixsanz  Â·  3Comments