JSON Search in laravel eloquent

I save the destinations field as json type in mysql

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

I would like to get all lines that match goa as recipients

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 5.3 Version

Model Name: Search

+6
source share
2 answers

It is likely to force a partially crude request 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();

if your query above works in SQL.

+9
source

In Laravel 5.6 and above, you can use the whereJsonContains method:

 Package::whereJsonContains('destinations',["Goa"])->get(); 

But not all databases support this: https://laravel.com/docs/5.6/queries#json-where-clauses

+1
source

Source: https://habr.com/ru/post/1263594/


All Articles