How to Change Redirect Path for a Form Request

Do you need to have a custom redirect path in a Laravel Form Request for some invalid data? Let’s say you have a public appointment form, but want to see if the form user’s name is in your system so you can validate they’re choosing the right appointment.

When their validation fails, say an existing customer uses a new customer time slot, you don’t want them to end up on the appointment form, you want them to bounce back to the calendar to pick the right time slot!

By default, Laravel will redirect the user to the form they were on, in this case, the appointment form, when validation fails.

The most natural place to check this might be in a Laravel validator after hook so we could do something like:


class AppointmentFormRequest extends FormRequest {
  // ... our rules and whatnot
  protected function after($validator) {
    // Let's see if the customer exists
    $customer = Customer::firstWhere('name', $input->name);
    if ($customer && $this->isUsingNewCustomerAppointment()) {
      $validator->errors()->add(
        'customer', "You're an existing customer and you should use an existing customer appointment."
      );
      $this->redirect = '/calendar'; // Redirect them to the calendar!
    }

    if (!$customer && $this->isUsingExistingCustomerAppointment()) {
      $validator->errors()->add(
        'customer', "You're a new customer and you should use a new customer appointment."
      );
      $this->redirect = '/calendar'; // Redirect them to the calendar!
    }
  }
}

So in this example, we check the customer, check their appointment, and if there’s a mismatch, we add an error to the validator, then change the redirect to the right URL, so Laravel sends the user to the right place!

The best part is that if the customer info is valid but there is another problem, the Laravel default will still hold and redirect back to the appointment intake form.

writing

I write about technology I'm using and the tech ecosystem.

speaking

I speak at tech and other events. You can see the recordings/slides.

resume

Here's my work history.

contact me

If you're interested in working together, let me know!