Laravel: Going back() after form validation errors

I’m SURE I must have done this before. Like…so many times. But this felt new today and is definitely worth remembering.

When you’re using forms in Laravel, you sometimes want a “cancel” or “back” button or link that takes you to where you were before. And Laravel provides a handy url() helper that gets a URL builder that you can add a previous() method call to get the referring URL:

url()->previous()

So you can put this as the href of a link and you’re done.

Well…unless…

You see, if you submit your form with errors, and Laravel’s validation is being used, your POST request, will result in the form page being reloaded. And the referrer – and therefore the previous() URL – will be the form page, because that’s where you came from.

So you need to remember the original previous URL between loads of the form page.

As always with Laravel there’s many ways to skin that cat. But I like this one: put a hidden field in your form to remember the original previous URL.

<input type="hidden"
       name="back_to"
       value="{{ old('back_to') ?: url()->previous() }}">

And then use that in your back/cancel button link:

<a class="btn btn-default"
   href="{{ old('back_to') ?: url()->previous() }}>
  Cancel
</a>

Note the use of the old() helper – because the POST to the form results in a redirect which loses the request data – so we need to grab it from the session.

Anyway, that’s a note to self, but maybe it helped you too.

Leave a Reply

Your email address will not be published. Required fields are marked *