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

LiamA's avatar
Level 1

Can't set cookies in middleware

I'm building a shopping cart SPA using Laravel and Vue.

Vue communicates with Laravel via the API, which is not a stateless as I'm using Sanctum for a cookie based session authentication services.

For guest users I want to store the cart info in a cookie. So I'm trying to set a cookie via a middleware I created with the following handle() method:

public function handle(Request $request, Closure $next)
{
    if(!$request->cookie('cart_id')){
    	$cart_id = "some value";
 return $next($request)->cookie(cookie()->forever('cart_id', $cart_id));
    }  
    return $next($request);
}    

I added this middleware to both 'api' and 'web' groups, but it doesn't seem to add the cookie no matter how many page requests I make.

Would appreciate some help with this Thanks

0 likes
2 replies
chaudigv's avatar

You should add Sanctum's middleware to your api middleware group within your app/Http/Kernel.php file. Read docs

LiamA's avatar
Level 1

@chaudigv Thanks for replying.

Turns out my problems was elsewhere. Sanctum's middleware was added properly, and when testing via the browser it did work. I was trying to get that result in my tests. It turns out that for testing you need to manually set cookies (?) via the withCookie() method.

I'm going to ask a new question about this.

Please or to participate in this conversation.