Laravel: Escape "LIKE" clause?
The other answer forgets about escaping the escape character itself, here is a more robust solution:
/**
* Escape special characters for a LIKE query.
*
* @param string $value
* @param string $char
*
* @return string
*/
function escape_like(string $value, string $char = '\\'): string
{
return str_replace(
[$char, '%', '_'],
[$char.$char, $char.'%', $char.'_'],
$value
);
}
Temporary solution:
$search = Input::query('sSearch', '');
if($search !== '') {
$escSearch = Util::escapeLike($search);
$paginatedBookings->where('first_name', 'LIKE', '%' . $escSearch . '%');
$paginatedBookings->orWhere('last_name', 'LIKE', '%' . $escSearch . '%');
}
class Util {
public static function escapeLike($str) {
return str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $str);
}
}
reference
I was hoping for something database-agnostic and more robust. I think you can change the escape char in MySQL, although I don't know why you would.