Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Created November 5, 2021 12:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/041da1e0f54efaad961d547acbb4e482 to your computer and use it in GitHub Desktop.
Save ziadoz/041da1e0f54efaad961d547acbb4e482 to your computer and use it in GitHub Desktop.
MySQL 8.0 JSON MEMBER OF Laravel Eloquent Macro
<?php
use Illuminate\Database\Query\Builder;
$memberOf = function ($value, string $column, string $path = '$', $boolean = 'and') {
return $this->whereRaw(
sprintf(
'? MEMBER OF(JSON_EXTRACT(%s, "%s"))',
$this->getGrammar()->wrap($column),
$path
),
[$value],
$boolean
);
};
Builder::macro('whereMemberOf', $memberOf);
Builder::macro('whereNotMemberOf', $memberOf);
Model::query()->whereMemberOf('a_json_column', 'value', '$[*]');
Model::query()->whereNotMemberOf('a_json_column', 'value', '$.field');
@bhuvidya
Copy link

Thanks heaps, this was real helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment