问题
I'm trying to retrieve a cookie from a middleware in Laravel 5.3 but it seems like $request->cookie('language') is empty. I'm guessing that it is only set after the middleware runs.
I read somewhere that I should use \Cookie::queued('language'), but it's still empty.
Is my only option using the $_COOKIE variable?
回答1:
When do you set this cookie?
Remember that cookies are stored in the browser, so the user needs to get the response in order for you to be able to retrieve the cookie later.
You should be able to get the cookie after the cookie is being set by a response that's successfully sent to the user. Remember also that if you use dd(), that doesn't let the cookie get created, because it skips all cookie headers from being sent to the user.
Another problem you might face for trying to get cookies from middleware is that it might not get decrypted automatically, so you'll have to do it yourself.
Example:
\Crypt::decrypt(Cookie::get('language'))
回答2:
If someone encounters this problem in 2019 with Laravel 5.8:
You will need to use \Crypt::decryptString(Cookie::get('language'))
or \Crypt::decrypt(Cookie::get('language'), false)
.
Otherwise it will try to unserialize the string and then strange things happen.
来源:https://stackoverflow.com/questions/40846244/get-a-cookie-in-laravel-5-middleware