简体   繁体   中英

Laravel query using LIKE does not return any result

Hi guys I'm currently stuck in this issue. I'm trying to search something on DB and doesn't return any results. Below are my codes.

Search string 1 = Boston Celtics

Search string 2 = Boston Celtics Can't

DB post_title = Boston Celtics Can't Let Bulls Loss Impact Difficult Stretch

QUERY

$data = $searchPost->where('post_title', 'like', '%'.$search.'%')
            ->orderBy('post_date', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

Search string 1 returns a result but search string 2 is not.

Simple, because your searching different string.

Search String 2 ".. Can't .." use Straight Quotes .

'

DB post_title ".. Can't .." use Curly Quotes .

'

For reference: Straight and curly quotes

My first guess would be that an apostrophe might be to blame - in SQL Server the concatenation operator is "+" so you also might want to make sure that is right. Maybe try removing an apostrophe character with:

replace($search, '''', '')

Four single quotes in Microsoft SQL is an escape sequence for a single quote.

Try the following code:

1) You code might be breaking string because of ' in can't .

$data = $searchPost->where('post_title', 'like', "%{$search}%")
            ->orderBy('post_date', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

Had the same problem before

try this

$data = $searchPost->where('post_title', 'like', '"%'.$search.'%"')
        ->orderBy('post_date', 'desc')
        ->offset($offset)
        ->limit($limit)
        ->get();

as you can see there is a " before the % at the start and another after % in the end.

If you see carefully you Can't in your search and your DB, the ' does not look the same

Can't vs Can't

When the ' is not the same, sure it can't be searched. Simple.

Had to use str_replace method to change apostrophe character

$search = str_replace('-', ' ', urldecode($request->input('search')));
$search = str_replace("'", "’", $search);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM