Ad

Setting Cookie In Laravel Custom Middleware

- 1 answer

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.

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.

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.

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

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.

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

Ad

Answer

You can obtain the response object in middleware like 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));
Ad
source: stackoverflow.com
Ad