Laravel’s whereJsonContains method

At my new job, they use a couple of different data column types in mySQL that I never actually knew existed until I started here. One of them is array and the other is json. Of course I knew these in coding, but never seen them as a database column type.

Anyway, I was given a task to try to filter a relationship on what would be originally stored in one of the array columns. Instead of writing a foreach loop to check, I found out that Laravel has a neat little where condition that checks JSON (which can be used for arrays too as it turns out) so you can filter for something instead of looping. The method is whereJsonContains() and it’s super handy.

Here’s an example of how it works. So I needed to filter out offices where the display key contained a footer option.

$site->offices()->whereJsonContains('display', ['footer'])->get();

Instead of returning 3 offices that are not supposed to be shown in the footer, it returned none. Saved me some lines of iterating over offices to check if the display is set with footer.

I believe this method was available starting in ver. 5.6 but I haven’t confirmed that. I did see other ways of handling this if you’re on an older version.

You can read more up on this at Laravel’s official documentation.