Reputation: 41
I have two tables in a database, package
and categories
.
package
has a field category_id
that contains data in this form ["1","11"]
and shows categories
data in the form of a checkbox.
Now, I want all the data from package
where category_id
equal to categories
id
.
Here's my code :
public function archive_packages(Request $request, $slug){
$title='Archive Packages';
$para='';
$slugs='archive-packages';
$categoryRow = Category::where('slug',$slug)->first();
$categoryID = $categoryRow->id;
$package = Packages::whereRaw('JSON_CONTAINS(category_id, \'["11"]\')')->get();
dd($package);
return view('pages.archive-packages',compact('title','para','slugs','package'));
}
I'm getting the following error :
SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION
pre.JSON_CONTAINS does not exist (SQL: select * from `packages` where
JSON_CONTAINS(category_id, '["11"]'))
Upvotes: 2
Views: 2476
Reputation: 11
Example JSON:
[ { "id": 11, "first_name": "Anthony", "last_name": "Ross", "language": "english", "grade": 1 } ]
If you have multiple values in json then you can try a loop like,
foreach($target as $target_result){
echo $target_result->id;
}
If you have only one record then try,
$target = Var::where('first_name', '=', $request->input('jsonArr'))->first();
return $jsonArr->id
Upvotes: 0
Reputation: 14268
There is a laravel method to do this, more details here
So please try:
Packages::whereJsonContains('category_id', '11')->get();
If your mysql version does not support json_contains
and you cannot upgrade it, then try this query:
Packages::where('category_id', 'like', '%"11"%');
Upvotes: 3
Reputation: 144
PHP has a built-in method json_encode() to easily encode arrays into JSON string format. We can implement it as: this we can use in laravel as well
$array = array('laptop','earphones','mouse'); return json_encode($array);
However, newer versions of Laravel also has a its own json() method which automatically sets relevant Content-Type and encodes JSON data:
$array = array('laptop','earphones','mouse'); return response()->json($array);
Upvotes: 0