Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 267
rider_moth Avatar asked Dec 19 '22 06:12

rider_moth


1 Answers

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;
like image 150
Imran Farooq Avatar answered Jan 03 '23 07:01

Imran Farooq