Home > database >  Not able to fetch the json data in laravel controller
Not able to fetch the json data in laravel controller

Time:02-22

I want to fetch the data from children field or get count of children.

I am fetching like this: $temp = json_decode($request->get('tempData');

Here is my json payload:

tempData:[{
      "id":"c625",
      "name":"Chapter 1",
      "children":[
         {
            "id":3,
            "type":"study material",
            "content":"Demo Study Material Title 2"
         },
         {
            "id":4,
            "type":"study material",
            "content":"Demo Study Material Title 3"
         },
         {
            "id":5,
            "type":"study material",
            "content":"Demo Study Material Title 4"
         }
      ],
      "type":"chapter"
   }
]

CodePudding user response:

You can get children count for all items on tempData array by using collection

collect(json_decode($request->get('tempData'), true))
->mapWithKeys(fn($item) => [$item['id'] => count($item['children'])])
->all();

to get result of children count for every id:

 [
    "c625" => 3
 ]

CodePudding user response:

You could create a new array and push children in that array with a foreach loop.

$temp = json_decode($request->get('tempData');
$children = array();
$child_count = 0;
foreach ($temp['children'] as $child) {
    $child_count  ;
    array_push($children, $child);
}
  • Related