rider_moth
rider_moth

Reputation: 75

How to store array cookie in laravel 5.4?

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.

Upvotes: 5

Views: 11383

Answers (2)

Imran Farooq
Imran Farooq

Reputation: 115

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 [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;

Upvotes: 7

Stan
Stan

Reputation: 491

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)));

Upvotes: 5

Related Questions