Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 Cookie Value

I am trying to get the value of a cookie.

1 When I use Laravel's request cookie helper:

$request->cookie('CookieName');

Laravel returns the cookie's name instead of its value.

2 When I dd() the the cookie() function:

dd(cookie('CookieName'));

I get:

#name: "CookieName"
#value: null
#domain: null
#expire: 0
#path: "/"
#secure: false
#httpOnly: true
-raw: false
-sameSite: null

3 When I use PHP's build in $_COOKIE function:

$_COOKIE['CookieName'];

I actually get the cookie's value.


Is there a way I can get Lavavel to return the cookie's value?

like image 779
Joshua Wieczorek Avatar asked May 21 '17 13:05

Joshua Wieczorek


2 Answers

The correct way to fetch the cookie value is as you've used

$request->cookie('name');

But the cookie helper method makes a new cookie, not fetches the value. So when you do dd(cookie('CookieName'));, its creating a cookie with that name and no value and returning it.

Laravel encrypts and decrypts the cookie value on the fly without any user intervention. Check how you're setting the cooking again and also make sure you've set the APP_KEY which will be used for the encryption. Changing this key would invalidate all the older cookies.

like image 149
Sandeesh Avatar answered Sep 20 '22 18:09

Sandeesh


Actually

$value = $request->cookie('name');

should give a value as you can read in doc.

I suspect that your cookie is set from some external code (not laravel code) for example it is created by jQuery plugin or something. In that situation you must add your cookie to EncryptCookies middleware $except table. Because all cookies created by the Laravel framework are encrypted and signed with an authentication code. All other cookies for example from jQuery plugin are not encrypted and signed by Laravel thus $request->cookie('name') can't see them or their value.

like image 27
arbogastes Avatar answered Sep 20 '22 18:09

arbogastes