Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a cookie in Laravel 5 middleware

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?

like image 783
Raz Weizman Avatar asked Dec 02 '25 09:12

Raz Weizman


2 Answers

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'))
like image 60
Ricardo Metring Avatar answered Dec 03 '25 23:12

Ricardo Metring


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.

like image 42
TimSch Avatar answered Dec 04 '25 00:12

TimSch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!