在laravel中反序列化数据 [英] unserialize data in laravel

查看:460
本文介绍了在laravel中反序列化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用serialize方法将购物车数据保存到orders表中,现在在我的订单查看"页面中,我想向用户显示它们以显示他们的订单历史记录.

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.

如何在PHP中将先前序列化的数据还原为可用的对象/数组?

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

保存数据的代码段:$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'));
}

推荐答案

您可以使用 map() 方法对整个集合进行反序列化购物车属性:

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

或者只是反序列化 Blade中的数据:

Or just unserialize the data in Blade:

@foreach ($orders as $order)
    {{ unserialize($order->cart)->someData }}
@endforeach

这篇关于在laravel中反序列化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆