Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Escape "LIKE" clause?

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.

like image 582
mpen Avatar asked Mar 30 '14 20:03

mpen


1 Answers

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
    );
}
like image 53
ntzm Avatar answered Sep 22 '22 08:09

ntzm