无法在 Laravel 4 中设置 cookie [英] Can't set cookies in Laravel 4

查看:20
本文介绍了无法在 Laravel 4 中设置 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是最新版本的 Laravel 4,无法设置 cookie:

I'm using the latest version of Laravel 4 and I can't set cookies:

Route::get('cookietest', function()
{
    Cookie::forever('forever', 'Success');
    $forever = Cookie::get('forever');
    Cookie::make('temporary', 'Victory', 5);
    $temporary = Cookie::get('temporary');
    return View::make('cookietest', array('forever' => $forever, 'temporary' => $temporary, 'variableTest' => 'works'));
});

查看脚本:

@extends('layouts.master')

@section('content')
    Forever cookie: {{ $forever }} <br />
    Temporary cookie: {{ $temporary }} <br />
    Variable test: {{ $variableTest }}
@stop

产量:

Forever cookie: 
Temporary cookie: 
Variable test: works

刷新页面或在一个路由中创建 cookie 并尝试在另一个路由中访问它们都没有关系.我可以确认没有通过上述操作设置 cookie.cookie 'laravel_payload' 和 'laravel_session' 以及 'remember_[HASH]' 确实存在,我可以使用 setcookie 使用常规 PHP 设置 cookie.

It doesn't matter if I refresh the page or create the cookies in one route and try to access them in another. I can confirm that no cookies are being set with the above operation. The cookies 'laravel_payload' and 'laravel_session' as well as 'remember_[HASH]' do exist and I can set cookies with regular PHP using setcookie.

在我能找到的任何地方都不会抛出或记录任何错误.我在本地运行 Linux Mint,在我的服务器上运行 Debian,都使用 nginx,我在这两个地方都有同样的问题.

No errors are thrown or logged anywhere that I can find. I'm running Linux Mint locally and Debian on my server, both with nginx and I have the same problem in both places.

推荐答案

Cookie 不是为了这样使用,它们是为下一个请求设置的,而不是为当前请求设置的.您必须手动将它们附加到您的响应中,如 文档中所述.

Cookies are not meant to be used like this, they are set for the next-request, not for the current request. And you have to manually attach them to your Response, as stated in the documentation.

所以这段代码

Cookie::forever('cookie', 'value');
$cookie = Cookie::get('cookie');

不会得到任何结果,因为在请求结束时没有附加 cookie.

will get no result because the cookie is not attached at the end of the request.

您可以尝试将其分成两条路线,例如

You can try it by splitting it in two routes like

Route::get('cookieset', function()
{
    $foreverCookie = Cookie::forever('forever', 'Success');
    $tempCookie = Cookie::make('temporary', 'Victory', 5);
    return Response::make()->withCookie($foreverCookie)->withCookie($tempCookie);
});


Route::get('cookietest', function()
{
     $forever = Cookie::get('forever');
     $temporary = Cookie::get('temporary');
     return View::make('cookietest', array('forever' => $forever, 'temporary' => $temporary, 'variableTest' => 'works'));
});

然后先访问 yoursite.local/cookieset 再访问 yoursite.local/cookietest 看看它是这样工作的,cookie 就会被设置.

then first access yoursite.local/cookieset and then yoursite.local/cookietestto see that it works this way and the cookie will be set.

这篇关于无法在 Laravel 4 中设置 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆