I am having troubles searching for a value in an array (of paths to images) within a MySQL JSON field. I want to check if a path to an image is stored in the database to prevent deleting the file.
Controller functions I have tried:
public function checkImage($filename){
$content = Content::whereRaw('JSON_CONTAINS(images->"$.path", lAeH88gIv4HeycQXHeMbT8yOyydybbOVhsSq9eAx.jpeg')->exists();
$content = Content::whereRaw('json_contains(images->path, \'["lAeH88gIv4HeycQXHeMbT8yOyydybbOVhsSq9eAx.jpeg"]\')')->exists();
$content = Content::whereRaw('json_contains(images->path, \'["' . $filename . '"]\')')->exists();
$content = Content::whereRaw('json_contains(images, \'["' . $filename . '"]\')')->exists();
return response()->json($content);
}
Example JSON:
{
"id": 4,
"images": [
{
"path": "abc/abc123.jpg",
"caption": "text",
"credits": "text"
},
{
"path": "abc/xyz123.jpg",
"caption": "text",
"credits": "text"
},
{
"path": "abc/827364527.jpg",
"caption": "text",
"credits": "text"
}
],
"created_at": "2017-12-20 11:40:16",
"updated_at": "2018-01-04 12:46:37"
}