How to work with cookies in Laravel 5.2

[亡魂溺海] 提交于 2019-12-04 03:34:04

You're creating a cookie object but you're not sending it with the response.

You can either, add it directly to your response in a controller

$cookie = Cookie::forever('cookie.clients', $clients);

return redirect('/client')->withCookie($cookie);

Or you can queue a cookie and use the AddQueuedCookiesToResponse Middleware to automatically add it to the Response.

Cookie::queue(Cookie::forever('cookie.clients', $clients));

return redirect('/client');

Here's another perspective.

If I understood correctly you've used Javascript to set the cookie on the client side, and you want to pick it up on the server side.

Laravel encrypts its cookies and when you use $request->cookies() you get the decrypted values, and retrieving the cookies from client side doesn't pass the decryption process and we get nulls. I guess, I haven't been able to dig out the appropriate source code :)

You can still use the raw PHP $_COOKIE['cookie_clients'] to retrieve the cookie set by client. Notice, . is converted to _ by PHP (as seen on php.net).

Alternatively, you could add the name of the cookie of interest into $except in Http/Middleware/EncryptCookies.php, which will allow you to pick it up with the more Laravel approach of $request->cookie().

I'm sure there are many other ways of going around Laravel here, hopefully this gives you an idea of where to look if you don't like either approach. Good luck.

Did you try to display the cookie via the Request object ?

$value = $request->cookie('name');

See laravel doc for more details : https://laravel.com/docs/5.2/requests#cookies

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