Nikki
130
1
Laravel

Getting info from a json_decode string

Posted 3 months ago by Nikki

I made a cart that when it's saved it is saved as a json_encode string. Everything looks great and kind of works. So what happens is that the cart is in a session then I save it to the database like this $order->cart = json_encode($cart). It saves nicely. The problem I have is that I can't access the product's title.

I can access for example the totalQty or the totalPrice by doing this {{ $cart->totalPrice }}, but not able to access anything else.

Here is the cart that is in my database

{"items":
    {"25":
        {"qty":"1",
        "price":259.58,
        "item":{
            "id":25,
            "title":"Product 2",
            "order":2,
            "supplier_code":"product-2",
            "description":"This is product 2",
            "price":"259.58",
            "image":"[\"product-2.jpg\"]",
            "image2":"[\"product-2.jpg\"]",
            "slug":"product-2",
            "created_at":"2018-08-23 12:19:44",
            "updated_at":"2019-02-11 09:17:14"}},

        "27":{
            "qty":"2",
            "price":6,
            "item":{
                "id":27,
                "title": "Product 3",
                "order":3,
                "supplier_code":"product-3",
                "description":"This is product 3",
                "price":"3.00",
                "image":"[\"product-3.jpg\"]",
                "image2":"[\"product-3.jpg\"]",
                "slug":"product-3",
                "created_at":"2018-08-23 12:22:18",
                "updated_at":"2019-02-11 09:17:38"
            }
        }
    },

    "totalQty":"2",
    "totalPrice":265.58
}

and this is how I'm decoding it

public function getInvoice($invoice_number)
{
    $orders = Order::where('invoice_number', $invoice_number)->get();

    foreach($orders as $order)
    {
        if($order->cart)
        {
            $cart = json_decode($order->cart);
        }else{
            $cart = [];
        }
    }

    return view('public.invoice', compact('cart'));
}

Please sign in or create an account to participate in this conversation.