Get a cookie in Laravel 5 middleware

不羁的心 提交于 2021-01-28 19:26:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!