Ad

Laravel 5: How To Handle Nested Objects In Json Request

- 1 answer

I just started working on Laravel 5. I am sending json request to my controller. It works fine for simple json. Now I have a scenario where json will be something like this

{
"orders":[
        {
          "user_id":"1",
          "product_id":"10"
        },
        {
            "user_id":"1",
          "product_id":"15"
        },
    ]
}

It can get more complex with nested objects. Inside my controller what I have been doing is simply like

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ordersController extends Controller 
{
    public function __construct( Request $request)
    {
      //$this->middleware('products.prodcutsList');
    }

    public function makeOrder(Request $request)
    {
        $order_data= $request->only('orders');
        print_r($order_data);
    }
}

response I get is looks like this

Array
(
    [orders] => 
)

Please guide how can I get this in an array.

Ad

Answer

I'm not sure that will resolve you problem but your json is not correct you have to remove extra comma in the end :

{
"orders":[
        {
          "user_id":"1",
          "product_id":"10"
        },
        {
            "user_id":"1",
          "product_id":"15"
        }, //remove this comma 
_________^ 
    ]
}

Note : You can use the following pretty website to validate you JSON jsonformatter.

Hope this helps.

Ad
source: stackoverflow.com
Ad