【问题标题】:How to store array cookie in laravel 5.4?如何在 laravel 5.4 中存储数组 cookie?
【发布时间】:2017-12-05 22:18:52
【问题描述】:

我在 laravel 5.4 中有这个功能,但我得到了错误。

$cart[$product->id] = $quantity;
var_dump($cart);
return redirect('catalogs')->withCookie(cookie()->forever('cart', $cart));

var_dump($cart) 包含这个:

array(1) { [1]=> string(1) "1" }

错误警告:

Method Symfony\Component\HttpFoundation\Cookie::__toString() must not throw an exception, caught ErrorException: Array to string conversion

如果我只传递字符串值(而不是数组),它会成功。有没有办法在 Laravel 中存储数组 cookie?

谢谢。

【问题讨论】:

  • 你试过序列化数组吗?
  • 是的,serialize($cart) 就是答案。虽然我希望 Laravel 框架可以处理在 cookie 中存储数组。

标签: php arrays laravel cookies laravel-5.4


【解决方案1】:

警告:不要使用序列化/反序列化 http://php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes

您可以将其存储为 JSON

 $user=['name'=>'Imran','email'=>'xyz*emphasized text@gmail.com'];
 $array_json=json_encode($user);
 return redirect('user')->withCookie(cookie()->forever( 'user',$array_json, 450000));

检索时

 $user=\Cookie::get('user');
       $user=json_decode($user);
echo $user->name;
echo $user->email;

【讨论】:

    【解决方案2】:

    只有字符串可以存储在 cookie 中。所以试试这个:

    $cart[$product->id] = $quantity;
    var_dump($cart);
    return redirect('catalogs')->withCookie(cookie()->forever('cart', serialize($cart)));
    

    【讨论】:

    • 好主意。感谢您解释只有字符串可以存储在 cookie 中,即使使用 Laravel 框架也是如此。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2018-10-15
    • 2018-12-22
    • 2012-07-08
    相关资源
    最近更新 更多