amrcodes's avatar

Where, LIKE, WhereIn

Hey!

I have a features_list column in my House DB and each row contains a long string of features and each feature separated with dash ' - ' : Coffee Maker-Tea Maker-Wifi-

In my frontend I have check boxes with values like Coffee Maker, Tea Maker, WiFi etc...

so now whenever I select multiple feature check boxes it is stored in array.

In my controller I find the House where it has Wifi for example using:

Home::where('features_list', 'LIKE', .%.$request->('feature').'%')->get();

Now the above query returns all the houses hat contain Wifi and only Wifi.

But i'm trying to get all the houses that has array of features, so whereIn comes in handy

but I can't use LIKE with whereIn cause it only takes 2 arguments.

 Home::whereIn('features_list', 'LIKE', .%.$request->('feature').'%')->get();
0 likes
7 replies
bugsysha's avatar

Create many-to-many relationship between house and features. That way you don't need LIKE and your queries are gonna probably be faster without it.

amrcodes's avatar

But House and Features are not different tables they are column in 1 table.

bugsysha's avatar
bugsysha
Best Answer
Level 61

Point is that your structure is not the best. But if you want to continue using it that way do following:

$query = Home::query();
foreach ($features as $feature) {
  $query->where('features_list', 'LIKE', '%'.$feature.'%');
}
$houses = $query->get();

But when you have bunch of records in your database you will probably experience slowdown.

1 like
amrcodes's avatar

Thank you so much and sorry for replying late!

Your help is much appreciated.

chaudigv's avatar

You can do something like

Home::where(function($query) use($request) {
	foreach($request->('feature') as $key => $feature) {
		if($key == 0) {
    	    $query->where('features_list', 'like', '%' . $feature . '%');
	    } else {
			$query->orWhere('features_list', 'like', '%' . $feature . '%');
        }
	}
})->get();
1 like
amrcodes's avatar

Thanks I'm sure it will work but I didn't try but it's same concept as @bugsysha answer, so thanks for helping!

Please or to participate in this conversation.