Searching for specific values within a JSON field that contains an array of objects can be accomplished using Eloquent in Laravel

I am attempting to search within a JSON field using Eloquent, but unfortunately, the search is not yielding any results.

This setup is on an Ubuntu server with PostgresSQL, Laravel 5.8, and Apache 2.

[{
    "value": "1",
    "label": "number"
},{
    "value": "2016",
    "label": "year"
},{
    "value": "Acer",
    "label": "species"
},{
    "value": "2",
    "label": "plant_qty"
}]
PlanificacionInfo::select('additional_data')->WhereJsonContains('additional_data', ["value" => "Pruning 2019"]);

The query is returning no results.

Answer №1

When working with PostgreSQL, remember that the object value must be enclosed in an array:

PlanificacionInfo::select('datos_complementarios')
    ->whereJsonContains('datos_complementarios', [["value" => "Escamonda 2019"]]);

To perform a case-insensitive search, you can use a raw expression like this:

PlanificacionInfo::select('datos_complementarios')
    ->whereJsonContains(
        DB::raw('lower("datos_complementarios"::text)'),
        [["value" => strtolower("Escamonda 2019")]]
    );

Answer №2

Did you attempt using a lowercase 'w' in ->whereJsonContains? For example:

PlanificacionInfo::select('datos_complementarios')
    ->whereJsonContains('datos_complementarios', ["value" => "Escamonda 2019"]);

According to the official documentation, you might need to adjust your code like this:

$users = PlanificacionInfo::select('datos_complementarios')
        ->whereJsonContains('datos_complementarios->value', 'YOUR SEARCH TERM HERE')
        ->get();

Furthermore, it seems that there is no matching JSON data for the query you provided in your question - does "Escamonda 2019" exist within your dataset?

Answer №3

Start by converting your JSON data into a PHP associative array:

//JSON data
$rawData = '[{
    "value": "1",
    "label": "number"
},{
    "value": "2016",
    "label": "year"
},{
    "value": "Acer",
    "label": "species"
},{
    "value": "2",
    "label": "plant_amount"
}]';

//Convert JSON to an associative array
$decodedArray = json_decode($rawData, true);

Use this function to filter and find matches with the key "value" equal to $searchWord:

//Function for searching a value in the array

function searchValueInArray($array, $searchWord)
{
  $resultArray = array_filter($array,
    function ($item) use ($searchWord) {
      return $item['value'] == $searchWord;
    }
  );
  return $resultArray;
}

Simply make a call to the function:

//Calling the function
$queryResult = searchValueInArray($decodedArray, "Acer");
var_dump($queryResult);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

What is the best way to compare a JSON object and a string in JavaScript?

Currently, I am working on developing the website layout for . Most of the data retrieval and display have been successful so far. However, when attempting to filter my search results to show only stop names associated with Subways, I encountered some err ...

"Utilize Vuejs to establish a binding between two objects when necessary

With the help of moment, my calendar generates 41 days. for (let x = 0; x < 42; x++) { context.add(1, 'd'); let day = { 'date': moment(context), 'events': [] }; } ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

Looking for a simple method to link JSON data to an svg element through Javascript?

Looking to harness the power of SVG for a basic graph creation, but uncertain about the process of assigning JSON data dynamically using a 'for loop' to draw rectangles within SVG. Seeking guidance on setting up 1 loop to assign each value for dr ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...