Cookie settings in Laravel Custom Middleware

I want to set a cookie in regular Laravel middleware. The idea is to set a cookie value at any time when a user visits my site through any landing page.

So what I did, I created a middleware named UUIDMiddleware. I use this middleware along with the Internet middleware on my routes. Below is its middleware code.

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 a cookie exists. If not, I transfer control to the following request.

The problem is that when setting a cookie with, return $responseI cannot transfer control to the next request. How to resolve this?

, cookie , cookie . , - cookie.

cookie . ?

+4
1

middleware :

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

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

    return $response;
}

, -

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

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

Source: https://habr.com/ru/post/1623818/


All Articles