Last active
July 15, 2025 13:45
-
-
Save macedd/7c8cb9a6967eb028e97f to your computer and use it in GitHub Desktop.
Laravel Unit Testing with persistent SessionID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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); | |
| } | |
| } |
The above example should return parent call in call() method otherwise returned response from the request will be null.
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
// set session_id cookie
$cookies = array_merge($cookies, $this->session_cookie);
return parent::call($method, $uri, $parameters, $cookies, $files, $server, $content);
}I found this pretty useful today, thanks for posting! A quick update though. About two years ago there was a
withCookiesmethod added to theMakesHttpRequestsclass. 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
I found this pretty useful today, thanks for posting! A quick update though. About two years ago there was a
withCookiesmethod added to theMakesHttpRequestsclass. The concept above still works but you can do something like below now: