Laravel 4:Cookie没有设置?

时间:2013-11-22 01:09:07

标签: cookies laravel laravel-4

我正试图在laravel中设置一个cookie:

    $cookie = Cookie::forever('knownWords', serialize($words));
                return Response::json(array('status' => "FAIL", 
                    "msg" => "Info stored in cookie!"))->headers->setCookie($cookie);

然后在不同的路线中,访问它,并将其作为json响应发送:

   $words = array();
        if(Cookie::has('knownWords')){
            $words = unserialize(Cookie::get('knownWords'))
        }
        return Response::json(array('status' => "FAIL", 
            "msg" => "Not logged in! Cookie info attached.",
            "data" => $words));        

我没有收到任何错误,但我可以确认它不会进入Cookie :: has()if语句。伙计们好吗?我对饼干很新!如果你需要知道我正在使用localhost和chrome!

编辑:我通过AJAX调用这些路由

2 个答案:

答案 0 :(得分:0)

显然我只需要使用composer来更新Laravel。现在它有效。 :d

答案 1 :(得分:-2)

尝试使用withCookie()。我的意思是,改变这个:

return Response::json(array(
    "status" => "FAIL", 
    "msg" => "Info stored in cookie!"
))->headers->setCookie($cookie);

为此:

return Response::json(array(
    "status" => "FAIL", 
    "msg" => "Info stored in cookie!"
))->withCookie($cookie);

这是我到目前为止所做的工作:

<?php // routes.php

Route::get('/', function() {
    return View::make('index');
});

Route::get('set', function()
{
    $words = ['foo', 'bar'];
    $cookie = Cookie::forever('knownWords', serialize($words));
    return Response::json(array('status' => "FAIL", "msg" => "Info stored in cookie!"))->withCookie($cookie);
});

Route::get('see', function()
{
    $words = array();

    if(Cookie::has('knownWords')){
        $words = unserialize(Cookie::get('knownWords'));
    }

    return Response::json(array('status' => "FAIL", 
        "msg" => "Not logged in! Cookie info attached.",
        "data" => $words));  
});

然后,视图(带有AJAX调用的简单html):

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
        $(function() {
            $.ajax({
                url: '{{ URL::to("set") }}',
                success: function(response) {
                    console.log(response);
                }
            });
        });
    </script>
</body>
</html>