To find out if the template_ids JSON field contains "any" values ββin the needle array, you will need to use several OR 'd JSON_CONTAINS , which requires MySQL 5.7:
$ids = ['1', '3', '48']; Post::where('accessable_to', 1) ->where(function ($query) use ($ids) { $firstId = array_shift($ids); $query->whereRaw( 'JSON_CONTAINS(template_ids, \'["' . $firstId . '"]\')' ); foreach ($ids as $id) { $query->orWhereRaw( 'JSON_CONTAINS(template_ids, \'["' . $id . '"]\')' ); } return $query; }); return Post::paginate(3);
The Laravel query constructor issues a query like:
SELECT * FROM "posts" WHERE "accessable_to" = ? AND ( JSON_CONTAINS(template_ids, '["1"]') OR JSON_CONTAINS(template_ids, '["3"]') OR JSON_CONTAINS(template_ids, '["48"]') )
Which goal entries contain any of these identifiers in the template_ids JSON field.
You may be interested in reading the relevant Laravel sentence.
source share