The error:
csrf_token(): Return value must be of type string, null returned
means that when your Volt component (or Blade view) calls csrf_token(), it returns null instead of a string. This usually happens because the application key is not set, or the session is not properly initialized in the test environment.
Why does this happen in tests?
- In a normal HTTP request, Laravel's middleware ensures the session is started and a CSRF token is generated.
- In a component test (like Volt or Livewire), if the session is not started,
csrf_token()returnsnull.
Solution
1. Ensure the session is started in your test
Add the withSession() method before rendering the component:
$component = Volt::test('appointments.create')->withSession([
'_token' => csrf_token() ?: Str::random(40),
]);
Or, if you want to ensure a token is always present:
use Illuminate\Support\Str;
$component = Volt::test('appointments.create')->withSession([
'_token' => Str::random(40),
]);
2. Make sure the APP_KEY is set in your .env.testing
If APP_KEY is missing, Laravel can't generate a CSRF token. Run:
php artisan key:generate --env=testing
Or manually set APP_KEY in your .env.testing file.
Example: Full Test
use Illuminate\Support\Str;
it('prefills patient and default date/time on mount', function () {
Patient::factory()->create(['id' => 12]);
Carbon::setTestNow(Carbon::parse('2025-01-01 12:00:00')); // Wednesday
$component = Volt::test('appointments.create')->withSession([
'_token' => Str::random(40),
]);
$expected = Carbon::today()->nextWeekday()->setHour(8)->setMinute(0);
$component
->assertSet('form.date', $expected->format('Y-m-d'))
->assertSet('form.time', $expected->format('H:i'));
$patient = $component->get('form.patient');
expect($patient)->not->toBeNull()
->and($patient->id)->toBe(12);
Carbon::setTestNow();
});
Summary
- Use
withSession(['_token' => ...])when testing components that use@csrforcsrf_token(). - Ensure your
APP_KEYis set in the testing environment.
This should resolve the csrf_token(): Return value must be of type string, null returned error in your Volt component test.