0
votes

Good day I need help on how to get the specific value on an array.I want to get the qty value and id value. The array output is like this

{"items":{"2":{"qty":1,"price":300,"item":{"id":2,"title":"LOTR","author":"James Cameron","price":300,"quantity":150,"created_at":"2020-08-24T13:35:36.000000Z","updated_at":"2020-08-24T13:38:52.000000Z"}}},"totalQty":1,"totalPrice":300}

As for the code

public function postCheckout(Request $request){

    if (!Session::has('cart')){
         return view('shop.shoppingcart');

    }
    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    $order = new Order();
    $order->cart = json_encode($cart);
    $order->address = $request->input('address');
    $order->name = $request->input('name');

Auth::user()->orders()->save($order);
   
    
   Session::forget('cart');   
}

public function findvalarray(){
    $order = Order::orderBy('created_at', 'desc')->limit(1)->get();
     return view("test", ['order' => $order]);

}

The one with $order->cart = json_encode($cart) is the part where all the products that have been added to cart.

While the findvalarray is the one to find the cart value in the database dont mind the limit cause I need it for selection of a specific date.

And this is the blade view

@foreach($order as $item) {{$item['cart']}}

@endforeach

Appreaciate the reply thank you

1

1 Answers

0
votes

Your $order->cart is in JSON format you need to json_decode() your cart to convert it to array|object so you can access it's value, in your blade you can do

@foreach($order as $item) 

   {{ dd(json_decode($item['cart'])) }}

@endforeach

The result will be an object that you can access like json_decode($item['cart'])->totalQty

{#260 ▼
  +"items": {#258 ▼
    +"2": {#257 ▼
      +"qty": 1
      +"price": 300
      +"item": {#251 ▼
        +"id": 2
        +"title": "LOTR"
        +"author": "James Cameron"
        +"price": 300
        +"quantity": 150
        +"created_at": "2020-08-24T13:35:36.000000Z"
        +"updated_at": "2020-08-24T13:38:52.000000Z"
      }
    }
  }
  +"totalQty": 1
  +"totalPrice": 300
}

If you want it as array you can do dd(json_decode($item['cart'], true)) this will give you

array:3 [▼
  "items" => array:1 [▼
    2 => array:3 [▼
      "qty" => 1
      "price" => 300
      "item" => array:7 [▼
        "id" => 2
        "title" => "LOTR"
        "author" => "James Cameron"
        "price" => 300
        "quantity" => 150
        "created_at" => "2020-08-24T13:35:36.000000Z"
        "updated_at" => "2020-08-24T13:38:52.000000Z"
      ]
    ]
  ]
  "totalQty" => 1
  "totalPrice" => 300
]

And you can access it like json_decode($item['cart'])['totalQty']