Skip to content

Instantly share code, notes, and snippets.

@macedd
Last active July 15, 2025 13:45
Show Gist options
  • Save macedd/7c8cb9a6967eb028e97f to your computer and use it in GitHub Desktop.
Save macedd/7c8cb9a6967eb028e97f to your computer and use it in GitHub Desktop.
Laravel Unit Testing with persistent SessionID
<?php
class ApiTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->session_id = session()->getId();
$this->session_cookie = [session()->getName() => $this->session_id];
}
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
// set session_id cookie
$cookies = array_merge($cookies, $this->session_cookie);
parent::call($method, $uri, $parameters, $cookies, $files, $server, $content);
}
public function testSession() {
// route return session()->getId()
$this->get("/api/session/")
->seeStatusCode(200);
$session_id = $this->response->original;
$this->get("/api/session/")
->seeStatusCode(200)
->see($session_id);
}
}
@bastianschwarz
Copy link

I found this pretty useful today, thanks for posting! A quick update though. About two years ago there was a withCookies method added to the MakesHttpRequests class. The concept above still works but you can do something like below now:

$this->withCookies($this->sessionCookie)->put(route('orders.update', $order['id']), ['item_id' => $this->additionalItem->id]);

Just stumbled upon this, looks like for JSON requests the cookies are only added when withCredentials is set to true, so doing a withCrendetials() call before might be needed.

        // get the session ID for the current session for later comparisons
        $sessionId = session()->getId();
        // activate with credentials so cookies are used for requests and the the session ID as cookie so the same one is used for all requests
        $this->withCredentials()->withCookie(session()->getName(), $sessionId);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment