Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chahal's avatar

Add a cookie to Middleware

I just created a new Middleware to create a new cookie named 'userKey'.

class UserCookies
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if(auth()->user() != null){
            return $next($request);
        }
        return $next($request)->cookie(cookie()->forever('userKey', Str::random(30)));
    }
}

Not sure why it isn't working. is there anything that i am missing ?

0 likes
5 replies
vincent15000's avatar

Can you try this ?

return $next($request)->withCookie(cookie()->forever('userKey', Str::random(30)));
chahal's avatar

I have already tried that, but that too didn't work.

1 like
thinkverse's avatar

Cannot replicate your issue, could it be the if statement that makes it not work? Remove the if statement and check if the cookie is set. Also, is the middleware attached to your route?

chahal's avatar

@thinkverse No, if statement isn't causing this issue. And yes, middleware is added to all web routes.

Please or to participate in this conversation.