Quick Tip: Using the Laravel from() Testing Helper

Tutorials

March 26th, 2021

laravel-from-helper.jpg

When testing with Laravel, sometimes it's helpful to test that a user was redirected back to the page where they "submitted" the form from.

Normally, if you just call the following the test will fail because the session doesn't have a previous page set.

1$this->post('/some-endpoint')->assertRedirect('/some-endpoint');`,

To fix this issue, Laravel provides a from() testing helper that, under the hood, sets a referer header and sets the _previous.url session variable to the url you pass in. Then, when you call redirect()->back() in your controller or somewhere else, Laravel knows where to redirect the user to.

1/** @test */
2public function the_user_is_redirected_back_to_the_edit_page()
3{
4 $user = User::factory()->create();
5 $post = Post::factory()->create();
6
7 $data = ['title' => 'Paul is Eric and Eric is Paul'];
8
9 $this->actingAs($user)
10 ->from('/posts/1/edit')
11 ->patch('/posts/1', $data)
12 ->assertRedirect('/posts/1/edit');
13}

Filed in:

Jason Beggs

TALL stack (Tailwind CSS, Alpine.js, Laravel, and Livewire) consultant and owner of roasted.dev.