在 Laravel 自定义中间件中设置 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34728924/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:02:00  来源:igfitidea点击:

Setting Cookie in Laravel Custom Middleware

laravellaravel-5.1laravel-5.2

提问by Gaurav Mehta

I want to set a cookie in a custom Laravel middleware. The idea is to set the cookie value any time a user visits my website through any landing page.

我想在自定义 Laravel 中间件中设置一个 cookie。这个想法是在用户通过任何登录页面访问我的网站时设置 cookie 值。

So what I did was I created a middleware named UUIDMiddleware. I am using this middleware along with web middleware in my routes. Below is its code from the middleware.

所以我所做的是我创建了一个名为UUIDMiddleware. 我在我的路由中使用这个中间件和 web 中间件。下面是来自中间件的代码。

if($request->hasCookie('uuid'))
{
    return $next($request);    
}
else
{
    $uuid = Uuid::generate();
    $response = new Response();
    return $response->withCookie(cookie()->forever('uuid', $uuid));
}

As you can see I am checking if cookie exists. If not, I am passing control to next request.

如您所见,我正在检查 cookie 是否存在。如果没有,我会将控制权传递给下一个请求。

The problem is when setting a cookie using return $response, I cannot pass control to next request. How do I resolve this?

问题是在使用 设置 cookie 时return $response,我无法将控制权传递给下一个请求。我该如何解决?

What happens in this case is if a cookie is not set, it sets a cookie and a blank screen shows up. If I refresh, I see the website with a cookie set.

在这种情况下会发生什么,如果没有设置 cookie,它会设置一个 cookie 并显示一个空白屏幕。如果我刷新,我会看到带有 cookie 集的网站。

There has to be a way to set cookie using middleware in the right way. How do I do it?

必须有一种方法以正确的方式使用中间件设置 cookie。我该怎么做?

回答by Rai

You can obtain the response object in middlewarelike so:

您可以像这样在中间件中获取响应对象:

public function handle($request, Closure $next)
{
    $response = $next($request);

    // Do something after the request is handled by the application

    return $response;
}

So you could do something like this

所以你可以做这样的事情

if($request->hasCookie('uuid')) {
    return $next($request);    
}

$uuid = Uuid::generate();
$response = $next($request);
return $response->withCookie(cookie()->forever('uuid', $uuid));

回答by Eric McWinNEr

If you're using Laravel 5.8 and like me you want a solution that allows you set the expiration time of the cookie instead of setting it to forever, you could also do something like this in the middleware:

如果您使用的是 Laravel 5.8 并且像我一样想要一个允许您设置 cookie 的过期时间而不是将其设置为永远的解决方案,您也可以在中间件中执行以下操作

public function handle($request, Closure $next)
{
    $time = time() + 60 * 60 * 24; //One day
    $res = $next($request);
    return $res->cookie('cookie_name', $cookieValue, $time, "/");
} 

This would set the cookie when the controller is done with the request and is returning a response.

这将在控制器完成请求并返回响应时设置 cookie。