Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Search in laravel eloquent

I am storing destinations field as json type in mysql

example column value ["Goa", "Moonar", "Kochi"]

I would like to get all rows that matches goa as destinations

However this row query returns the desired result

SELECT * FROM `packages` 
WHERE JSON_CONTAINS(destinations, '["Goa"]');

But what is the eloquent equivalent of the above query??

Laravel version 5.3

Modelname :Search

like image 420
shellakkshellu Avatar asked Jan 30 '17 17:01

shellakkshellu


People also ask

How to search JSON data in Laravel?

laravel is provide the " whereJsonContains " function to search on JSON fields in laravel 8. here we add one " geo_location_info " field add in " users " table and you want to search any of the values from it then it will help you in searching.

What is toArray () in laravel?

What is toArray () in laravel? toArray is a model method of Eloquent, so you need to a Eloquent model, try this: User::where('name', '=', 'Jhon')->get()->toArray(); http://laravel.com/docs/eloquent#collections. Follow this answer to receive notifications.25-Dec-2013.

What is JSON encode in laravel?

Laravel JSON is a small package that makes encoding and decoding JSON a breeze with exceptions thrown on error immediately: A simple wrapper around json_encode() and json_decode() for catching any errors without executing json_last_error() .

What is eloquent serialization?

October 5th, 2021. Eloquent Serialize is a Laravel package to serialize and unserialize Eloquent query builder objects.


1 Answers

Probably forced to use a partially raw query like:

use DB; (top of file definition)

DB::table('packages')->whereRaw('json_contains(destinations, \'["Goa"]\')')->get();

And if you have a model:

Package::whereRaw('json_contains(destinations, \'["' . $keyword . '"]\')')->get();

assuming your query above works in SQL.

like image 68
Jonathan Avatar answered Sep 18 '22 21:09

Jonathan