HOW TO CREATE FILE UPLOADER & VALIDATE A FILE UPLOAD IN LARAVEL

HOW TO CREATE FILE UPLOADER &VALIDATE A FILE UPLOAD
HOW TO CREATE A FILE UPLOADER &VALIDATE A FILE UPLOAD IN LARAVEL

HOW TO CREATE A FILE UPLOADER:
Sometimes we need the user to upload a file. For this purpose, we need a file uploader.
TO create a File uploader Follow these steps:
1.  Create a route in our routes.php file to hold the form:
Route::get('fileform', function()
{
return View::make('fileform');
});
2.  Create the fileform.php View in our app/views directory:
<h1>File Upload</h1>
<?= Form::open(array('files' => TRUE)) ?>
<?= Form::label('myfile', 'My File') ?>
<br>
<?= Form::file('myfile') ?>
<br>
<?= Form::submit('Send it!') ?>
<?= Form::close() ?>
3.  Create a route to upload and save the file:
Route::post('fileform', function()
{
$file = Input::file('myfile');
$ext = $file->guessExtension();
if ($file->move('files', 'newfilename.' . $ext))
{
return 'Success';
}
else
{
return 'Error';
}
});
HOW TO VALIDATE A FILE UPLOAD:
Sometimes we need to allow user to upload a file. We can add restriction on which kind of file the user can upload. Using Laravel's Validator class, we can check for a specific file type and limit the upload to a certain file size.
Follow these steps to validate a file upload in Laravel:
  Create a route for the form in our routes.phpfile:
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";
}
}
});


Comments