Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Cookie in Laravel Custom Middleware

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?

like image 938
Gaurav Mehta Avatar asked Jan 11 '16 18:01

Gaurav Mehta


People also ask

How do I set browser cookies in Laravel?

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.

What is middleware and create one in Laravel?

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.

What is Laravel cookie?

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.

What is default middleware in Laravel?

Laravel framework comes with several middlewares, including midlewares for — authentication and CSRF protection. The default middleware are located in the app/Http/Middleware directory.


1 Answers

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));
like image 160
Rai Avatar answered Nov 15 '22 07:11

Rai