Quick Tip: Using the Laravel from() Testing Helper
Published on by Jason Beggs
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.
$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.
/** @test */public function the_user_is_redirected_back_to_the_edit_page(){ $user = User::factory()->create(); $post = Post::factory()->create(); $data = ['title' => 'Paul is Eric and Eric is Paul']; $this->actingAs($user) ->from('/posts/1/edit') ->patch('/posts/1', $data) ->assertRedirect('/posts/1/edit');}
TALL stack (Tailwind CSS, Alpine.js, Laravel, and Livewire) consultant and owner of designtotailwind.com.