Raz Weizman
Raz Weizman

Reputation: 89

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?

Upvotes: 2

Views: 3282

Answers (2)

TimSch
TimSch

Reputation: 1462

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.

Upvotes: 4

Ricardo Metring
Ricardo Metring

Reputation: 422

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'))

Upvotes: 5

Related Questions