【问题标题】:How to set cookies in laravel 5 independently inside controller如何在控制器内部独立地在 laravel 5 中设置 cookie
【发布时间】:2015-10-09 14:11:34
【问题描述】:

我想在 Laravel 5 中独立设置 cookie

即不想使用

return response($content)->withCookie(cookie('name', 'value'));

我只想在某个页面中设置cookie并在其他页面中检索

创作可以是这样的

$cookie = Cookie::make('name', 'value', 60);

但是我怎样才能在某些控制器本身中检索这些 cookie 呢?

【问题讨论】:

标签: php laravel cookies laravel-5


【解决方案1】:

你可以试试这个:

Cookie::queue($name, $value, $minutes);

这会将 cookie 排队以供稍后使用,稍后当响应准备好发送时,它将与响应一起添加。您可以在Laravel 网站上check the documentation

更新(Retrieving A Cookie Value):

$value = Cookie::get('name');

注意:如果您在当前请求中设置了 cookie,那么您将能够在下一个后续请求中检索它。

【讨论】:

  • 请检查文档(答案中给出的链接),您会在那里找到所有内容。
  • 他要求 Laravel 5。这个例子是 Laravel4。
  • 不适用于我的 Laravel 5。Cookie 课程似乎已经消失了。
  • @DanJones,我会尽快检查,您使用的是哪个版本 (5.0/5.2/5.2...) - 5?
  • 5.0.35 虽然,我对 Laravel 还是很陌生,所以我可能缺少一些东西。
【解决方案2】:

如果你想设置 cookie 并在请求之外获取它,Laravel 不是你的朋友。

Laravel cookie 是 Request 的一部分,因此如果您想在 Request 对象之外执行此操作,请使用好的 'ole PHP setcookie(..) 和 $_COOKIE 来获取它。

【讨论】:

  • setcookie() 不工作,是否有任何设置可能会干扰此操作?
【解决方案3】:

我的朋友,你走对了。现在如果你想在项目中的任何地方检索cookie,只需输入此代码$val = Cookie::get('COOKIE_NAME'); 而已! For more information how can this done click here

【讨论】:

  • 嗨,我用 $value=Cookie::get('name');但是当我回显 $value 它显示我空白,在此之前我使用 Cookie::queue('name',$name);请帮我解决这个问题
  • 如果 cookie 不存在,$value 将为空。看到这个链接:laravel-recipes.com/recipes/49/…
  • @Jigs Virani 你错了。如果你想在请求之外设置 cookie 并在 Laravel 中获取它,Laravel 不是你的朋友。甚至您提供的链接都说; “这与 Request::cookie() 基本相同”。所以,Nil 抱怨是对的。
【解决方案4】:

这是一个带有解释的示例代码。

 //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可以通过forever方法永久设置,如下代码所示。

$response->withCookie(cookie()->forever('name', 'value'));

检索 Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多