Skip to content

Instantly share code, notes, and snippets.

@mikehins
Last active November 23, 2018 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehins/c3e69c8ad4ca8a1581917bccb27e7b0f to your computer and use it in GitHub Desktop.
Save mikehins/c3e69c8ad4ca8a1581917bccb27e7b0f to your computer and use it in GitHub Desktop.
Query json by key with laravel
public function whereJSON($key, $value)
{
$fields = explode('.', $key);
if (count($fields) !== 2) {
die('Please use this format field_name.key to query JSON');
}
$fieldname = $fields[0];
return $this->whereRaw($fieldname . ' REGEXP \'"' . $fields[1] . '":"([^"]*)' . $value . '([^"]*)"\'')->get()
->map(function ($item) use ($fieldname) {
return json_decode($item->$fieldname);
});
}
$q = (new Model)->whereJSON('meta.key', 'Value');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment