Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Setting a request header in a Livewire test

It's not as simple as it looks

Joel Clermont
Joel Clermont
2026-11-26

From our daily Laravel tips email. Get the next one in your inbox.

I was testing a Livewire form that records the visitor's user agent when it's submitted:

public function submit(Request $request): void
{
    ContactMessage::create([
        'email' => $this->email,
        'user_agent' => $request->userAgent(),
    ]);
}

Livewire's test helper has a withHeaders() method, so this seemed like the obvious test:

Livewire::withHeaders(['User-Agent' => 'Test Agent'])
    ->test(ContactForm::class)
    ->set('email', '[email protected]')
    ->call('submit');

But the saved user agent wasn't "Test Agent". It was "Symfony", which is the default user agent for a test request.

It turns out the header only applies to the initial render. Every set() and call() after that is its own request, and none of them carry the custom header. So mount() would see "Test Agent", but submit() never does.

I also tried $this->withServerVariables() from the regular test case. That one doesn't reach the Livewire test client at all, not even on the initial render.

What did work was setting the header myself, once the request reaches the router. Every Livewire test request still goes through Laravel's routing, which fires a RouteMatched event with the current request. That's the same request object that gets injected into submit().

protected function setUserAgent(string $userAgent): void
{
    Event::listen(
        RouteMatched::class,
        fn(RouteMatched $event) => $event->request->headers->set('User-Agent', $userAgent),
    );
}

Now the test reads the way I wanted it to:

$this->setUserAgent('Test Agent');

Livewire::test(ContactForm::class)
    ->set('email', '[email protected]')
    ->call('submit');

self::assertSame('Test Agent', ContactMessage::sole()->user_agent);

The listener runs on every request in the test, so the header is there for the initial render and every action after it.

If a Livewire test ever ignores a header you set, check which request your code actually reads it from.

Here to help,

Joel

P.S. Our testing course has a lesson on testing Livewire components, from rendered data and pagination to form submissions and validation.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.