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! 😎

Interested in learning more?

If you want to take a deeper dive into security, become a Laravel Security in Depth subscriber to receive monthly In Depth emails about Laravel Security concepts, and access our intentionally vulnerable demo site, plus weekly security tips to help you write secure code.

In the past we have covered Using Placeholders Safely, Escaping Output Safely and SQL Injection, as well as how Encryption works in Laravel, plus you can access all past emails, so you can learn about the topics that interest you today.

Leave a Reply

Your email address will not be published.