Sanitizing Form Data Before Validating in a Laravel 5 Form Request

Forms

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at December 8, 2015 7:22 pm

Sometimes submitted data requires a bit of additional work prior to validation

If you've kept up with the blog posts over at EasyLaravelBook.com, then you know I often refer to form requests as my favorite Laravel 5 feature. They're a fantastic way to separate form validation logic from a controller action's primary duty, resulting in often far slimmer action logic. If you're not familiar with form requests, have a look at this blog post.

When using form requests you might occasionally desire to filter the data prior to validation. For instance, if a user submits a phone number, and you asked the user to provide digits only (such as 6148675309) yet the user somehow manages to submit 614-867-5309, the submission is still valid although malformatted, so it doesn't necessarily make any sense to force the user to enter the number (and potentially other form data) anew. You can forego the hassle by first sanitizing the input prior to validation, however the process for doing so inside a form request isn't so obvious.

The Request class includes a number of different methods, including all(), which retrieves all of the request data. You can filter desired data attributes by overriding this method inside your form request like so:

class RegistrationRequest extends Request
{

    ...

    public function all()
    {
        $attributes = parent::all();

        $attributes['phone_num'] = preg_replace("/[^0-9]/", '', $input);

        $this->replace($attributes);

        return parent::all();

    }

    ...

}

WIth the method override in place, there's nothing else to do! Laravel will automatically call this method when validation begins, meaning any filtered data will be available when the associated validation occurs.