Validating a file upload in laravel

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>’) ?>
foreach ($messages as $msg)
echo $msg;
<?= Form::open(array(‘files’ => TRUE)) ?>
<?= Form::label(‘myfile’, ‘My File (Word or Text doc)’) ?>
<?= Form::file(‘myfile’) ?>
<?= 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’
Using Forms and Gathering Input
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
return Redirect::to(‘fileform’)->withErrors($validation)
$file = Input::file(‘myfile’);
if ($file->move(‘files’, $file
return “Success”;
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”.

Leave a Reply

Your email address will not be published. Required fields are marked *