简体   繁体   English

如何在laravel 5.4中存储数组cookie?

[英]How to store array cookie in laravel 5.4?

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. 谢谢。

Only strings can be stored in a cookie. 只有字符串可以存储在cookie中。 So try this: 试试这个:

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

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 text@gmail.com'];
 $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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM