php 如何在控制器内部独立地在 Laravel 5 中设置 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31516762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set cookies in laravel 5 independently inside controller
提问by The Alpha
I want to set cookies in Laravel 5 independently
我想在 Laravel 5 中独立设置 cookie
i.e., Don't want to use
即,不想使用
return response($content)->withCookie(cookie('name', 'value'));
return response($content)->withCookie(cookie('name', 'value'));
I just want to set cookie in some page and retrieve in some other page
我只想在某个页面中设置 cookie 并在其他页面中检索
Creation can be like this
创作可以是这样
$cookie = Cookie::make('name', 'value', 60);
$cookie = Cookie::make('name', 'value', 60);
But how can i retrieve those cookies in some controller itself ?
但是我怎样才能在某些控制器中检索这些 cookie 呢?
回答by The Alpha
You may try this:
你可以试试这个:
Cookie::queue($name, $value, $minutes);
This will queue the cookie to use it later and later it will be added with the response when response is ready to be sent. You may check the documentationon Laravel
website.
这将使 cookie 排队以供稍后使用,稍后将在响应准备好发送时将其添加到响应中。您可以查看Laravel
网站上的文档。
Update (Retrieving A Cookie Value
):
更新(Retrieving A Cookie Value
):
$value = Cookie::get('name');
Note: If you set a cookie in the current request then you'll be able to retrieve it on the next subsequent request.
注意:如果您在当前请求中设置了 cookie,那么您将能够在下一个后续请求中检索它。
回答by Jeffz
If you want to set cookie and get it outside of request, Laravel is not your friend.
如果你想设置 cookie 并在请求之外获取它,Laravel 不是你的朋友。
Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.
Laravel cookie 是 Request 的一部分,因此如果您想在 Request 对象之外执行此操作,请使用好的 'ole PHP setcookie(..) 和 $_COOKIE 来获取它。
回答by Jigs Virani
You are going right way my friend.Now if you want retrive cookie
anywhere in project just put this code $val = Cookie::get('COOKIE_NAME');
That's it!
For more information how can this done click here
你走对了,我的朋友。现在如果你想cookie
在项目中的任何地方检索,只需输入这段代码$val = Cookie::get('COOKIE_NAME');
就可以了!
有关如何完成此操作的更多信息,请单击此处
回答by gauravbhai daxini
Here is a sample code with explanation.
这是一个带有解释的示例代码。
//Create a response instance
$response = new Illuminate\Http\Response('Hello World');
//Call the withCookie() method with the response method
$response->withCookie(cookie('name', 'value', $minutes));
//return the response
return $response;
Cookie can be set forever by using the forever method as shown in the below code.
可以使用以下代码所示的永久方法永久设置 Cookie。
$response->withCookie(cookie()->forever('name', 'value'));
Retrieving a Cookie
检索 Cookie
//'name' is the name of the cookie to retrieve the value of
$value = $request->cookie('name');