I'm wanting to parse this array of objects into something PHP can read so that I can save it into the database. Here's the array of objects, this is from a console log, and is what is being sent to my axios post:
"user_id": 4,
Array [
Object {
"cartID": "33S",
"id": 33,
"image": "http://myurl/uploads/5db88f40c857dtest.jpg",
"name": "testt",
"quantity": 1,
"size": "S",
},
Object {
"cartID": "32S",
"id": 32,
"image": "https://dummyimage.com/600x400/000/fff",
"name": "pottery",
"quantity": 1,
"size": "S",
},
Object {
"cartID": "34S",
"id": 34,
"image": "http://myurl/uploads/5db8918fac485test.jpg",
"name": "Nature",
"quantity": 1,
"size": "S",
},
]
On PHP I have:
public static function AddOrder(Request $request)
{
$add = DB::table('Orders')->insert([
'user' => $request->user_id
]);
$items = json_decode($request->cartItems, true);
foreach ($items as $item) {
DB::table('order_items')->insert([
'order_id' => DB::table('orders')->latest('user_id')->first(),
'product' => $item->id,
'quantity' => $item->quantity,
'size' => $item->size
]);
}
return $add;
}
Whenever I try this I always end up get an error cartItems can't be null. I've even tried just returning cartItems before anything in AddOrder is ever ran but it just says that it's null. I am using axios to send it like:
axios.post('http://myurl/api/orders/create', {
cartItems: cart,
user_id: user.id
})
.then(res => {
console.log(res.data)
})
.catch(err => {
console.log(err)
})
I've also tried another way
let newReq = {
user_id: 1
};
for(let i = 0; i < cart.length; i++) {
Object.keys(cart[i]).forEach((key) => {
let newkey = 'cartItems[' + i + '][' + key + ']';
newReq[newkey] = cart[i][key];
});
}
With that being sent, on Laravel to respond to the client I use:
return response()->json($request->all());
I get
Object {
"cartItems[0][cartID]": "33S",
"cartItems[0][id]": 33,
"cartItems[0][image]": "http://trayvonnorthern.com/Edgewood-API/public/uploads/5db88f40c857dtest.jpg",
"cartItems[0][name]": "testt",
"cartItems[0][quantity]": 1,
"cartItems[0][size]": "S",
"cartItems[1][cartID]": "32S",
"cartItems[1][id]": 32,
"cartItems[1][image]": "https://dummyimage.com/600x400/000/fff",
"cartItems[1][name]": "pottery",
"cartItems[1][quantity]": 1,
"cartItems[1][size]": "S",
"cartItems[2][cartID]": "34S",
"cartItems[2][id]": 34,
"cartItems[2][image]": "http://trayvonnorthern.com/Edgewood-API/public/uploads/5db8918fac485test.jpg",
"cartItems[2][name]": "Nature",
"cartItems[2][quantity]": 1,
"cartItems[2][size]": "S",
"user_id": 1,
}
when I do
return response()->json($request->cartItems);
It returns nothing.
$request->user_idis it null too? Please, add add($request->all());in your question.dd($request->all());in the very start of yourAddOrder, and ensure that you have got any data from axios requestddreturns a generated HTML page with the contents of the response in a readable format. In your case, returningresponse()->json($request->all())should suffice