问题
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