Ashish kumar singh
Ashish kumar singh

Reputation: 328

Not able to fetch the json data in laravel controller

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"
   }
]

Upvotes: 0

Views: 305

Answers (2)

Suhail Kawsara
Suhail Kawsara

Reputation: 515

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
 ]

Upvotes: 3

Loostie
Loostie

Reputation: 1

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);
}

Upvotes: 0

Related Questions