【问题标题】:Set a cookie in Laravel 5+ without response在 Laravel 5+ 中设置 cookie 没有响应
【发布时间】:2016-11-03 15:45:24
【问题描述】:

我正在尝试在一个不会返回响应的函数中设置一个 cookie。该函数是从中间件调用的。

中间件:

// Verify user
        $userId = $userService->verify($email, $key);
        if ($userId) {
            $userService->authenticate($userId, $key);

            return $next($request);
        } else {
            return response('Unauthorized', 401);
        }

正在调用 $userService->authenticate:

// Get user
    $user = $this->getById($id);
    // Get user zipcode
    $user->zipcode = $this->getZipcodeById($id);
    // Set session
    Session::set('user', $user);

    if (!Cookie::has('user_forever')) {
      // SET COOKIE   
    }

我尝试在身份验证中返回响应,但它不起作用。我无法让它工作..所以我感谢所有帮助!

提前致谢

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以将queue() 用作:

    Cookie::queue('key', 'value', 10);
    

    【讨论】:

    • 该死,我读到 Cookie::queue 在 Laravel 5 中已被删除,但它确实有效!谢谢
    【解决方案2】:

    according to docs你可以使用cookie助手生成一个cookie实例,

    $cookie = cookie('name', 'value', $minutes);
    

    但除非它附加到响应实例,否则它不会被发送回客户端。尝试从如下中间件发送

    $response = $next($request);
    
    return $response->cookie($cookie);
    

    未经测试的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 2018-08-29
      • 2012-03-25
      • 2015-08-13
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多