Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bufferoverflow's avatar

Query like whereIn() in array column

Hello!

Can't find in the documentation a way to search for a specific value in a table calumn.

Take for example a Real Estate website:

A house has a table 'features' that is casted as an array. So the features are stored like this: ["pool", "garden", "air_conditioner"].

If i want to query all the properties that has pool feature, i would like to make something like this, of course this example won't work:

Property::whereIn('features', 'pool')->get()

I thought the following solution but i don't know if it's the way to go. What do you think?

Property::where('features', 'like', "%"{$feature}"%")->get()

Thanks!

0 likes
6 replies
xxRockOnxx's avatar

That's the problem with bad db design. Never also heard people storing array in db except for json. Not sure why json also but that's also a pain.

If it's in production already I think the LIKE might be the way to go, if not try refactoring out the features to another table. By doing that, you can do eloquent relationships and do something like

Property::find(1)->features()->where()->get()

1 like
bufferoverflow's avatar

Okay i understand the point, i'll try to refactor the structure.

But i don't get the find(1) in your query example. Wouldn't be like this?

Property::with('features')->where('features.name', 'pool')->get()

Thanks.

Cronix's avatar
Cronix
Best Answer
Level 67
$featureType = 'pool';

$property = Property::with(['features' => function($query) use ($featureType) {
   $query->where('name', $featureType);
}])->get();

or to search on multiple values

// properties that have a pool, or air conditioner
$featureTypes = ['pool', 'air conditioner'];

$property = Property::with(['features' => function($query) use ($featureTypes) {
   $query->whereIn('name', $featureTypes);
}])->get();

See the "Constraining Eager Loads" part

https://laravel.com/docs/5.6/eloquent-relationships#eager-loading

3 likes
xxRockOnxx's avatar

@bufferoverflow was just an example to show you that you can do eloquent relationships like that.

@cronix pretty sure that's not what he wants. What that does is get all Properties but you are just constraining the eager loaded relationship.

What he wants is get Properties that has the specified Features. Most likely it will be a ManyMany relationship and then will do wherePivot('feature_id', 1)

Please or to participate in this conversation.