Skip to content
Advertisement

How to use CASE WHEN IN in Laravel database query builder

I have users table and a followers table. I’m doing a search to get all the users with a specific keyword, but I want the ones which are followers of the current user to appear first. I can get all the followers id’s in a subquery, so my idea was to do something like this:

I’ve been trying to get this in my Laravel controller, but I can’t find the way. How could I use this SQL select in my Laravel controller? How could translate this SQL code to the Laravel Database Query Builder?

What I have already tried:

Following @Bassel Hossam answer, I wrote the following code:

It seems very very close, but I’m still geting a “SQLSTATE[HY093]: Invalid parameter number” error. The generated SQL is the following:

It seems that somehow it’s always adding the same number of question marks than the number of question marks generated in the $placeholders variable. What I can’t understand is why its generating it in an array that I think that should only be related to $matchingUsersId.

dd($matchingUsersId, $friendsId) is returning the following:

Finall working code based on @Bassel Hossam answer:

Advertisement

Answer

the syntax for in condition should be like CASE WHEN id IN (?,?,?) THEN so you need to add ? with the count of $friendsId

so you should use the following

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement