Ayrton
Ayrton

Reputation: 2303

Is it possible to submit an array of objects?

I'm using Laravel 5.3, and I'm having trouble submitting arrays of objects to my controller. Is it possible? And if not, is there a workaround so that I can submit multiple objects at once?

Example request:

let req = {
    'data[]': [
        { id: 1, name: 'test1' },
        { id: 2, name: 'test2' }
    ]
};

Then, to test, I simply returned the contents of the request:

public function testArray(Request $request) {
    return response()->json($request->all());
}

And got this result:

data: [
    "[object Object]",
    "[object Object]"
]

Upvotes: 0

Views: 584

Answers (3)

Natvarsinh Parmar - bapu
Natvarsinh Parmar - bapu

Reputation: 1138

In your js

let req = [
    { id: 1, name: 'test1' },
    { id: 2, name: 'test2' }
];

var baseurl = window.location.protocol + "//" + window.location.host;
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
    url: baseurl + "/test-data",
    type: 'post',
    data:{
        req:req
    },
    cache: false,
    success: function(response) {
        console.log(response);
    }
});

In controller:

public function testArray(Request $request) {
     $post = $request->all();

     return response()->json($post);
}

In route file: (web.php)

Here I used DemoController you can replace with your controller name

Route::post('/test-data', 'DemoController@testArray');

Result:

req: (2) […]
​​
0: Object { id: "1", name: "test1" }
​​
1: Object { id: "2", name: "test2" }
​​
length: 2

Upvotes: 1

Kiril Lukiyan
Kiril Lukiyan

Reputation: 187

return is often having issues when displaying objects/arrays. Try simply:

dd($request->all())

instead of return, you'll be surprised :)

Upvotes: 0

Source Edin
Source Edin

Reputation: 101

In your case, result is an array of objects, result[0] is the first object. To access the id for example, you would use result[0]['id']. You can use a for loop for example to see real data.

Also I think u can use json_encode.

Hope it helps!

Upvotes: 0

Related Questions