2

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.

6
  • When you use $request->user_id is it null too? Please, add a dd($request->all()); in your question. Commented Oct 30, 2019 at 13:30
  • yeah when I do a return $request, I just get an empty array Commented Oct 30, 2019 at 13:41
  • as Jean said, please do dd($request->all()); in the very start of your AddOrder, and ensure that you have got any data from axios request Commented Oct 30, 2019 at 14:18
  • Well I'm using laravel as a REST API. Isn't just returning a response to my client side gonna achieve the same thing? Commented Oct 30, 2019 at 14:35
  • dd returns a generated HTML page with the contents of the response in a readable format. In your case, returning response()->json($request->all()) should suffice Commented Oct 30, 2019 at 14:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

no problem. This is now allowing me to get cartItems. awesome! Now there's one more issue. I've tried a foreach that looks something like: foreach($cartItems as $cartItem) { return response()->json($item->name)} but get an error.
just returning $item returns a single object but not able to access the properties. Sorry this is my first time attempting to use a client side cart and convert it into a PHP array
@MikeShiv Are you accessing the item properties using object notation or array notation?
object notation. Since I'm on a mobile app I just get a 500 error so hard to tell there but when I try on postman I just get a invalid argument for foreach
@MikeShiv Try using array notation like this: $size = $request->cartItems[0]['size'];. Laravel doesn't parse your objects back into objects, but into keyed arrays.
|
0

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] 
//      ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.