unserialize data in laravel

北城以北 提交于 2020-02-24 15:59:16

问题


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'));
}

回答1:


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



回答2:


Sure you can use built-in unserialize() function from previous answers.

But

Avoid using unserialize() in your code because of exloit:

https://www.notsosecure.com/remote-code-execution-via-php-unserialize/ https://www.php.net/manual/en/function.unserialize.php

I would use secure simple lib from Magento 1: https://github.com/bragento/magento-core/tree/1.9/lib/Unserialize

$parser = new Unserialize_Parser();
$parser->unserialize($yourStringWithArray)



回答3:


serialize is just a built-in, variable handling, PHP function. The counterpart of this is unserialize.



来源:https://stackoverflow.com/questions/48125903/unserialize-data-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!