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?
Creating a CookieCookie can be created by global cookie helper of Laravel. It is an instance of Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of Illuminate\Http\Response class to call the withCookie() method.
Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This chapter explains you the middleware mechanism in Laravel. Laravel includes a middleware that verifies whether the user of the application is authenticated or not.
Cookies. All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client.
Laravel framework comes with several middlewares, including midlewares for — authentication and CSRF protection. The default middleware are located in the app/Http/Middleware directory.
The response object in middleware is returned by the $next
closure, so you could do something like this:
if($request->hasCookie('uuid')) {
return $next($request);
}
$uuid = Uuid::generate();
return $next($request)
->withCookie(cookie()->forever('uuid', $uuid));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With