Validating a file upload

If we want to allow users to upload a file through our web form, we may want to restrict which kind of file they upload. Using Laravel's Validator class, we can check for a specific file type, and even limit the upload to a certain file size.

Getting ready

For this recipe, we need a standard Laravel installation, and an example file to test our upload.

How to do it...

Follow these steps to complete this recipe:

  1. Create a route for the form in our routes.php file:
    Route::get('fileform', function()
    {
        return View::make('fileform');
    });
  2. Create the form view:
    <h1>File Upload</h1>
    <?php $messages =  $errors->all('<p style="color:red">:message</p>') ?>
    <?php
    foreach ($messages as $msg)
    {
        echo $msg;
    }
    ?>
    <?= Form::open(array('files' => TRUE)) ?>
    <?= Form::label('myfile', 'My File (Word or Text doc)') ?>
    <br>
    <?= Form::file('myfile') ?>
    <br>
    <?= Form::submit('Send it!') ?>
    <?= Form::close() ?>
  3. Create a route to validate and process our file:
    Route::post('fileform', function()
    {
        $rules = array(
            'myfile' => 'mimes:doc,docx,pdf,txt|max:1000'
        );
        $validation = Validator::make(Input::all(), $rules);
        
        if ($validation->fails())
        {
    return Redirect::to('fileform')->withErrors($validation)->withInput();
        }
        else
        {
            $file = Input::file('myfile');
            if ($file->move('files', $file->getClientOriginalName()))
            {
                return "Success";
            }
            else 
            {
                return "Error";
            }
        }
    });

How it works...

We start with a route to hold our form, and then a view for the form's html. At the top of the view, if we get any errors in validation, they will be echoed out here. The form begins with Form::open (array('files' => TRUE)), which will set the default action, method, and enctype for us.

Next we create a route to capture the post data and validate it. We set a $rules variable as an array, first checking for a specific mime type. There can be as few or as many as we want. Then we make sure the file is less than 1000 kilobytes, or 1 megabyte.

If the file isn't valid, we navigate the user back to the form with the error messages. The $error variable is automatically created in our view if Laravel detects a flashed error message. If it is valid, we attempt to save the file to the server. If it saves correctly, we'll see "Success", and if not, we'll see "Error".

There's more...

One other common validation for files is to check for an image. For that, we can use this in our $rules array:

'myfile' => 'image'

This will check to make sure the file is either a .jpg, .png, .gif, or .bmp file.

See also

  • The Creating a file uploader recipe