如何在 Laravel 5.4 中存储数组 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44872142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store array cookie in laravel 5.4?
提问by rider_moth
I have this function in laravel 5.4 but I get error.
我在 laravel 5.4 中有这个功能,但出现错误。
$cart[$product->id] = $quantity;
var_dump($cart);
return redirect('catalogs')->withCookie(cookie()->forever('cart', $cart));
var_dump($cart) contains this:
var_dump($cart) 包含这个:
array(1) { [1]=> string(1) "1" }
Error warning:
错误警告:
Method Symfony\Component\HttpFoundation\Cookie::__toString() must not throw an exception, caught ErrorException: Array to string conversion
If I passed just string value (not array), it success. If there any way to store array cookie in Laravel?
如果我只传递字符串值(不是数组),它就成功了。如果有什么方法可以在 Laravel 中存储数组 cookie?
Thank you.
谢谢你。
回答by Stan
Only strings can be stored in a cookie. So try this:
cookie 中只能存储字符串。所以试试这个:
$cart[$product->id] = $quantity;
var_dump($cart);
return redirect('catalogs')->withCookie(cookie()->forever('cart', serialize($cart)));
回答by Imran Farooq
Warning: Do not use serialize/unserialize http://php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes
警告:不要使用序列化/反序列化 http://php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes
You can store it as JSON
您可以将其存储为 JSON
$user=['name'=>'Imran','email'=>'xyz*emphasized [email protected]'];
$array_json=json_encode($user);
return redirect('user')->withCookie(cookie()->forever( 'user',$array_json, 450000));
On retrieval
检索时
$user=\Cookie::get('user');
$user=json_decode($user);
echo $user->name;
echo $user->email;