Outputting cookie in Laravel-5/Blade

3.9k Views Asked by At

I have cookie date stored in a serialized array which I would like to access via the Blade template.

If a cookie value is set matching the current field name, then I want to show it. I am currently using the following code, but I'm not sure how to access the array value.

{{{ Cookie::has('myBookingDetails') ? Cookie::get('myBookingDetails') : old('name') }}}

The value of the myBookingDetails cookie looks like this:

a:4:{s:4:"name";s:13:"Joe Bloggs";s:5:"email";s:29:"[email protected]";s:5:"phone";s:11:"0777777777";s:3:"reg";s:6:"123456";}

How can I access the "name" value via Blade?

2

There are 2 best solutions below

3
On

The data is serialized. You need to use unserialize() function to get the data.

$data = unserialize(Cookie::get('myBookingDetails'));

$name = $data['name']

Check for existence before use.

0
On

Don't know if previous answer solved your enigma, but I could give some help.

I fought with a similar case. Seems that in template - in laravel 5.1 - I couldn't access directly to cookies:

Cookie::get('cookiename') simply returns null cookie('cookiename') returns a Symfony\Component\HttpFoundation\Cookie, but $cookie->getValue() returns (again) null.

The good old $_COOKIE['cookiename'] returns the right cookie, so you could simply go with unserialize( $_COOKIE['myBookingDetails'] )['name']; !

PS: It should be better to handle with cookies in controller and pass a normal variable to the view!