In this case typically the CSRF token is invalid or the session cannot be read properly.
Since switching to file works fine, it clearly points to a problem with the database session handling, not the CSRF system itself.
1. Is the sessions table present and correctly structured?
Bacause Laravel needs a valid sessions table for database session driver to works correctly.
php artisan session:table
php artisan migrate
You should have columns like:
- id (string/uuid)
- user_id (nullable)
- ip_address (nullable)
- user_agent (nullable)
- payload
- last_activity (int)
2. Database Connection for Sessions Is Working
- Ensure the
DB_CONNECTIONin.envis correct. - Test if session rows are inserted on request. You can add
\Log::info(Session::getId());in a controller and check if the session appears in the sessions table.
3. Session Middleware Order and Kernel Check
Ensure these middlewares are present in the correct order in bootstrap/app.php:
<?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) {
$middleware->web([
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Missing or misordered middleware can cause Laravel not to read/write sessions correctly.
Final Tip: Use Laravel Debugbar
Install Laravel Debugbar to see session content in real-time:
composer require barryvdh/laravel-debugbar --dev
Then check if session is being persisted between requests.