How to store array cookie in laravel 5.4?

我的未来我决定 提交于 2020-04-06 22:16:06

问题


I have this function in laravel 5.4 but I get error.

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

var_dump($cart) contains this:

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?

Thank you.


回答1:


Only strings can be stored in a cookie. So try this:

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



回答2:


Warning: Do not use serialize/unserialize http://php.net/manual/en/function.unserialize.php#refsect1-function.unserialize-notes

You can store it as 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;


来源:https://stackoverflow.com/questions/44872142/how-to-store-array-cookie-in-laravel-5-4

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