简体   繁体   中英

Parsing and looping through a javascript array of objects in PHP Laravel

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.

Axios doesn't seem to accept the request format I used on my previous answer, so I deleted it. However, it seems to accept requests in this format (which is what you initially used. my mistake, really):

let request = {
    user_id: 1,
    cartItems: [
        {
            "cartID": "33S",
            "id": 33,
            "image": "http://myurl/uploads/5db88f40c857dtest.jpg",
            "name": "testt",
            "quantity": 1,
            "size": "S",
        },
        {
            "cartID": "32S",
            "id": 32,
            "image": "https://dummyimage.com/600x400/000/fff",
            "name": "pottery",
            "quantity": 1,
            "size": "S",
        },
        {
            "cartID": "34S",
            "id": 34,
            "image": "http://myurl/uploads/5db8918fac485test.jpg",
            "name": "Nature",
            "quantity": 1,
            "size": "S",
        }
    ]
}

Then, you can send the request object with axios.post . To access it on your back-end, use $items = $request->cartItems . There is no need to parse it.

When sending Objects or Arrays to Laravel API using Axios, try converting the payload to JSON string.

Try this on your client side

const your_payload_object = { user_id : 1, cart_items:[{id:1},{id:2},{id:3}] };

axios.post(url, JSON.stringify(your_payload_object), {"Content-type": "application/json"})

You can access the data on laravel like

$userId = $reequest->user_id;

$cart_items = $request->cart_items;

// Which will be an array as given below
//
// $cart_items = 
//      [ 
//         ["id" => 1], 
//         ["id" => 2], 
//         ["id" => 3] 
//      ];

Try sending a request with this structure:

{
    "user_id": 4,
    "cartItems[0][cardID]": "33S",
    "cartItems[0][id]": 33,
    "cartItems[0][image]": "http://myurl/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://myurl/uploads/5db8918fac485test.jpg",
    "cartItems[2][name]": "Nature",
    "cartItems[2][quantity]": 1,
    "cartItems[2][size]": "S"
}

And accessing it in this structure on your back-end:

$items = $request->cartItems;

Assuming the variable names and structure on your question, you can refactor it with this code:

let newReq = {
    user_id: user.id
};

for(let i = 0; i < cart.length; i++) {
    Object.keys(cart[i]).forEach((key) => {
        let newkey = 'cartItems[' + i + '][' + key + ']';

        newReq[newkey] = cart[i][key];
    });
}

In case you're wondering, even if you send your request in that format there is no need to parse it on server. Laravel does that for you. So the request at the beginning of the answer actually becomes a structured array with keys corresponding to your indexes and properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM