nionta's avatar

Like search is not working properly in Eloquent

here is my query:

    ->when(!empty($name), function($query) use ($name){
                return $query->where('infos.name', 'like', $name.'%')
                    ->orWhere('infos.name', 'like', '% '.$name.'%');
            })

but, its not working for finding 2nd or last word of a name; as,in "Mohoshin Ara Tahera", if I search "Mohoshin" it works, but if I search "Ara" or "Tahera" or "Mohoshin Ara" it's not showing any result.

0 likes
12 replies
KimG's avatar

I'm not sure if this is the culprit, but I think you have an unnecessary space in your query -

->orWhere('infos.name', 'like', '% '.$name.'%');

Should be...

->orWhere('infos.name', 'like', '%'.$name.'%');
nionta's avatar

@KIMG - I have tried both before, but none of them works

druc's avatar

@nionta I tested some version of that query on my end and there's no reason why it shouldn't work.

You posted only a part of your query, maybe the problem is elsewhere?

Also, there's no reason to have two "LIKE"s for the same column&variable.

munazzil's avatar

Your using when and also there is same query has two times.Use as like below and check.

     ->when(!empty($name), function($query) use ($name){
            return $query->where('infos.name', 'like', '%'.$name.'%');
               
        })
Snapey's avatar

Do you have a join in the query? I'm wondering why you specify the table?

This format

    ->when(!empty($name), function($query) use ($name){
                return $query->where('infos.name', 'like', '%'.$name.'%');
            })

will match any part of the name

eg if the column contains "Mohoshin Ara Tahera" then it would match "mohoshin" or just "shin"

This may return many more matches than you like.

Like @druc I cannot see anything fundamentally wrong with your query, and the second form with the space obviously attempts to split on whole words.

Maybe there is something else in the query or the column name, with the table specified, is not working as expected

nionta's avatar

yeah I have found the problem, thanks to all

Snapey's avatar

What? What? you can't leave us hanging like that, we've been puzzling over your issue.

2 likes
jlrdw's avatar

I thought about it all night, tossed and turned.

How to keep snapey in suspense for 24 hours?

I'll tell you tomorrow.

amitsolanki24_'s avatar

Try this

>when(!empty($name), function($query) use ($name){
                return $query->where('infos.name', 'like', '%'. name.'%');
            })

Snapey's avatar

@amitsolanki24_ who?

You clearly missed the subtlety of the space after the % giving a word break % $name%

Anyway this was 4 years ago so we are all over it now.

Please or to participate in this conversation.