How can I escape a LIKE
clause in Laravel/Eloquent? e.g.,
$search = Input::query('sSearch', '');
if($search !== '') {
$paginatedBookings->where('first_name', 'LIKE', '%' . $search . '%');
}
If $search
contains a %
or _
they need to be escaped.
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
);
}
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