Laravel Display Array on blade with "unserialize"

  arrays, json, laravel, php

im facing an issue to retrive an array from my database and display it on my blade.

So to understand my work, im actualy saving "Cart" informations on my "Orders Table" with Serialize the Products

public function store(Request $request)
    {

        $order = new Order();
        $order->user_id = request('user_id');
        $order->wilaya = request('wilaya');
        $order->province = request('province');
        $order->address = request('address');
        $order->phone = request('phone');
        $order->quantity = request('quantity');
        $order->subtotal = request('total');
        $order->status = request('status');

        $products = [];
        $i = 0;

        foreach (Cart::content() as $product){
            $products['product_' . $i][]= $product->name;
            $products['product_' . $i][]= $product->options->color;
            $products['product_' . $i][]= $product->price;
            $products['product_' . $i][]= $product->options->size;
            $products['product_' . $i][]= $product->options->image;
            $products['product_' . $i][]= $product->qty;
            $i++;
        }


        $order->products = serialize($products);
        //dd($order);
        if(Cart::count() <= 0){
            return redirect('/products');
        }else{
        $order->save();
        Cart::destroy();
        return view('checkout.thankyou');
        }

    }

So when i try to retrive my data from the "Products" column with Unserialize on my show ressource

public function show($id)
    {
        $orderShow = Order::find($id);
        $arr = unserialize($orderShow->products);
        dd($arr);
        return view('dashboard.order.show', compact('orderShow', 'arr'));
    }

I get this result

array:2 [▼
  "product_0" => array:6 [▼
    0 => "T-Shirt Fashion 3"
    1 => "black"
    2 => 1300.0
    3 => "S"
    4 => "QFh840we7wZBKO790A6wFlipJB1ASaCpt3zJhJl8.png"
    5 => 1
  ]
  "product_1" => array:6 [▼
    0 => "T-Shirt Fashion"
    1 => "green"
    2 => 1200.0
    3 => "L"
    4 => "CdMVwEJcMQbJjMp70UhRnkNQnRmWxzAGiWKxFeWN.png"
    5 => 1
  ]
]

result of dd($arr) with image

I also try this

$json = json_encode(unserialize($orderShow->products));

And i get this result

"{"product_0":["T-Shirt Fashion 3","black",1300,"S","QFh840we7wZBKO790A6wFlipJB1ASaCpt3zJhJl8.png",1],"product_1":["T-Shirt Fashion","green",1200,"L","CdMVwEJcMQbJjMp70UhRnkNQnRmWxzAGiWKxFeWN.png",1]} ◀"

So i dont know how to deal with these arrays on my blade, i know that i need a Foreach loop to display it on the right way, but i have no idea how to proceed.

Source: Laravel

Leave a Reply