2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Talha Malik
  • 1,509
  • 3
  • 22
  • 44

2 Answers2

1

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

You send your data as form data. Use the php input wrapper:

$input = file_get_contents('php://input'); // json
print_r(json_decode($input)); // decode to php array
schellingerht
  • 5,726
  • 2
  • 28
  • 56