#In a Table Filter, how can I query a JSON element that is an array instead of a value?

3 messages · Page 1 of 1 (latest)

burnt prawn
#

Hi,

In a Table Filter, how can I query a JSON element that is an array instead of a value?

For example, Let's assume the following in a column named data:

{
  "genre": "Science Fiction",
  "tags": [
    "future",
    "robots",
    "speculative"
  ]
}

Using the following ENUMs:

Genre Enum

case SciFi = 'Science Fiction';
case Romance = 'Romance';
case History = 'History';
case Fantasy = 'Fantasy';

Tags Enum

case Future = 'Future';
case Robots = 'Robots';
case Speculative = 'Speculative';
case HeroJourney = 'Hero\'s Journey';
case Travel = 'Travel';

If I want to filter by genre, I can do this, which works fine:

SelectFilter::make('data->genre')
    ->label('Genre')
    ->multiple()
    ->options(GenreEnum::class),

However, the same does not work for tags because they are arrays. Anything I pick never matches.

SelectFilter::make('data->tags')
    ->label('Tags')
    ->multiple()
    ->options(TagEnum::class),

How can I create a filter using the tags in data->tags?

fringe frostBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

burnt prawn
#

Figured it out:

SelectFilter::make('data->tags')
    ->label('Tags')
    ->multiple()
    ->options(TagEnum::class)
    ->query(function (Builder $query, array $data): Builder {
        return $query->whereJsonContains(
            'data->tags',
            $data['values']
        );
    })