Categories
Development LaraSec Security

Always Pass User Input Through a Validator

This is the seventh security tip from Laravel Security in Depth, which was sent out on November 9th. You can subscribe to receive more tips and monthly In Depth emails covering of Laravel Security.

Don’t trust user input.

Don’t trust user input.

And one more for good measure…

Don’t trust user input.

You should always pass user input through a validator before you use it, and here are a few reasons why:

  1. It forces you to define explicit rules which state exactly what sort of input is allowed in each field.
  2. You’re far less likely to have unexpected data that causes your application to do unexpected things.
  3. You have control over which fields are passed into a model for mass-assignment.
  4. Your user interface can understand and display friendly errors to your users with minimal effort on your part.

Check out the docs for the many ways to use a validator in Laravel.

My preferred method is within controller actions on the Request object, or using A FormRequest object for more complicated forms.

/**
 * Store a new blog post.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validated = $request->validate([
        'title'      => ['required', 'unique:posts', 'max:255'],
        'body'       => ['required', 'string'],
        'publish_at' => ['nullable', 'date'],
    ]);

    // $validated contains only valid user input

    $post = Post::create($validated);

    // ...
}

Go forth and validate all the things! 😎

Leave a Reply

Your email address will not be published.