phplaravelsessionlaravel-12

Laravel 12 creates a new session on each request


I created a new Laravel 12 application following the Installation guide. The project is generated correctly and I ran all migrations.

When I run php artisan --version I get: Laravel Framework 12.20.0 (And using PHP version 8.4.8).

The problem is that each time I go to the website a new session is created, so no state is preserved. I know this because the SESSION_DRIVER=database and each time I go to the page a new row in the database is added.

In my routes/web.php I've got this (just for testing):

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    error_log(json_encode(session()->all()));

    if (session()->get('installed')) {
        return view('installed');
    }

    return view('welcome');
});

The error_log just prints an empty object to the console. Then I put a test string in the session like this: session()->put('test', 123);.

Now when the session is printed it prints this: {"test": 123}. If I then remove the session()->put() line and reload the session is empty again.

I've changed nothing in the config and my bootstrap/app.php looks like this:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        api: __DIR__ . '/../routes/api.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

My session configuration in the .env file is this:

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

The application is running in an iframe, when I go directly to localhost:8000 I don't have this problem.

I am serving the app using php artisan serve and using Ngrok to serve it over https. The ngrok link is then put in an iframe.

<iframe width="100%" height="800" frameborder="0" scrolling="auto" src="https://<ngrok-domain>&lang=en" title="App"></iframe>

Looking at my Chrome devtools application tab I see the session cookie: Chrome Devtools Cookie Tab

I looked online and a potential cause was an empty line before the <?php tag but I looked at all files and none had this issue.

Why is my app creating a new session each time?


Solution

  • After lots of trail and error and a very helpful discussion with @Emad Kerhily I fixed it.

    Problem was that the cookie was being set on the parent of the iframe and not on the domain of the iframe itself.

    Fix was setting SESSION_SECURE_COOKIE=true and SESSION_SAME_SITE=None in the .env.