简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM