Last active
November 23, 2018 18:47
-
-
Save mikehins/c3e69c8ad4ca8a1581917bccb27e7b0f to your computer and use it in GitHub Desktop.
Query json by key with laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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