3

I saved my cart data to the orders table with the serialize method, now in my orders 'view' page, I want to display them to the user to show their order history.

How can I revert the previously serialized data to usable objects/arrays within PHP?

The code snippet of where I save the data: $order->cart = serialize($cartItems);.

The method I try to return my orders index view:

/**
 * Action to receive all orders from the current
 * logged-in user. This action will return the
 * 'front.orders' view with the orders compacted inside.
 *
 * @return orders view
 */
public function orders() {
    // get the orders from the current logged in user
    $orders = Order::where('user_id', '=', Auth::user()->id)->get();

    // view the `front.orders` page passing in the `orders` variable
    return view('front.orders', compact('orders'));
}
Blauharley
  • 4,186
  • 6
  • 28
  • 47
mafortis
  • 6,750
  • 23
  • 130
  • 288

3 Answers3

5

You can use map() method to unserialize cart property for the whole collection:

$orders = $orders->map(function($i) {
    $i->cart = unserialize($i->cart);
    return $i;
});

Alternatively, you could use an accessor to automatically unserialize property:

public function getCartAttribute($value)
{
    return unserialize($value);
}

Or just unserialize the data in Blade:

@foreach ($orders as $order)
    {{ unserialize($order->cart)->someData }}
@endforeach
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • if i use map, how do i use my query to only get logged user orders and not all users? – mafortis Jan 06 '18 at 09:45
  • @mafortis the code you've shown will get only logged in user's orders. Just use map after you're getting orders. – Alexey Mezenin Jan 06 '18 at 09:47
  • I GET ERROR OF `unserialize(): Error at offset 0 of 91 bytes` – mafortis Jan 07 '18 at 08:05
  • 1
    @mafortis it's not related to the question, so you may start another answer if you'll not handle it by yourself. You can start by reading [this](https://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset). – Alexey Mezenin Jan 07 '18 at 08:08
  • ok its working now and here is my blade code, `@foreach($orderss as $order)
  • {{$order->cart}}
  • @endforeach` this is screenshot, https://ibb.co/mSU2nG how do i get info properly? – mafortis Jan 07 '18 at 08:16