I created a new class, which extends the StartSession Middleware (referenced in app/Middleware/Kernel.php
, inside the web
group).
<?php
namespace App\Http\Middleware;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Symfony\Component\HttpFoundation\Response;
class StartSession extends \Illuminate\Session\Middleware\StartSession
{
/**
* Start the session for the given request.
*
* @param Request $request
* @param Session $session
* @return Session
*/
protected function startSession(Request $request, $session): Session
{
return tap($session, function ($session) use ($request) {
$session->setRequestOnHandler($request);
if (Cookie::get(config("session.cookie"))) {
$session->start();
}
});
}
/**
* Add the session cookie to the application response.
*
* @param Response $response
* @param Session $session
* @return void
*/
protected function addCookieToResponse(Response $response, Session $session)
{
if (!auth()->check()) {
return;
}
if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
$response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie(
$session->getName(), $session->getId(), $this->getCookieExpirationDate(),
$config['path'], $config['domain'], $config['secure'] ?? false,
$config['http_only'] ?? true, false, $config['same_site'] ?? null
));
}
}
}
The two importants part are :
if (Cookie::get(config("session.cookie"))) {
$session->start();
}
This part prevents the session from being created when the user wasn't already authed.
- in addCookieToResponse() :
if (!auth()->check()) {
return;
}
This part prevents Laravel from setting the cookie as long as the user is not authed.