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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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();

Method 3

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.

Method 4

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.

Method 5

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.

Method 6

Had to use str_replace method to change apostrophe character

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x