There is a withSession method available to you for this
https://laravel.com/docs/8.x/http-tests#session-and-authentication
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
im working on an e-commerce system where i try to make a shopping cart for guest users that are not logged in. In my Feature tests the session id wont persist so when trying to validate if the user can add a shopping cart item because the shopping cart?
$location = Location::first();
$cart = ShoppingCart::currentOrCreate($location);
$sessionId = Session::getId();
// dump(sessionId, cart->session_id) here returns a $sessionId that is equal to $cart->session_id;
$sessionName = Session::getName();
$product = $location->products()->first();
$data = [
'productId' => $product->id,
'cartId' => $cart->id
];
$response = $this->withCookies([$sessionName => $sessionId])->post(route('shopping-cart.add-item'), $data); // sessionId() within that controller is different than the one dumped in line 4
$response->assertOk();
$cart->refresh();
$this->assertTrue($cart->items->count() == 1);
Within the static function ShoppingCart::currentOrCreate($location) it creates a new shopping cart model based on session()->getId() and saves it to the shopping carts session_id property.
$cart->session_id = $session()->getId();
$cart->location_id = $location->id;
$cart->save();
Even though im doing $this->withCookies([$sessionName => $sessionId]) my session()->getId() within that request has a different session id then my initial created one at ShoppingCart::currentOrCreate($location).
I cant figure out why and i cant get my test to work since my $response->assertOk() returns a 403 (which it should when the session id is not the same)
Please or to participate in this conversation.