Home » Laravel File Upload Form Tutorial With Example

Laravel File Upload Form Tutorial With Example

Last updated on May 20, 2022 by

We will see the Laravel file upload form tutorial with an example in this post. We can easily upload different types of files like pdf, doc, docx, csv, txt, png, gif, zip, etc. using the Laravel file upload form. We will add the validation rules to only allow particular file formats in the Laravel. Let’s just dive into it.

Step 1: Install Laravel

If you already have installed Laravel on your local machine then you can skip this step. You can easily install the fresh version of Laravel by running the below command in your terminal.

composer create-project --prefer-dist laravel/laravel demo-app

Step 2: Create Routes

We need to add two routes in routes/web.php file to perform the Laravel file upload form. The first GET route is to show the file upload form and another route for the POST method to store the file or image in Laravel.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;

Route::get('file-upload', [ FileUploadController::class, 'getFileUploadForm' ])->name('get.fileupload');
Route::post('file-upload', [ FileUploadController::class, 'store' ])->name('store.file');

Step 3: Create FileUploadController

Let’s create a FileUploadController and let’s add those two methods that we have added in the routes file getFileUploadForm() and store().

app/Http/Controllers/FileUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileUploadController extends Controller
{
    public function getFileUploadForm()
    {
        return view('file-upload2');
    }

    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:pdf,xlxs,xlx,docx,doc,csv,txt,png,gif,jpg,jpeg|max:2048',
        ]);

        $fileName = $request->file->getClientOriginalName();
        $filePath = 'uploads/' . $fileName;

        $path = Storage::disk('public')->put($filePath, file_get_contents($request->file));
        $path = Storage::disk('public')->url($path);

        // Perform the database operation here

        return back()
            ->with('success','File has been successfully uploaded.');
    }
}

Notes: To validate doc, docx you need to create mimes.php in config directory and add the following content.

config/mimes.php

<?php

return [
    'doc'  => array('application/msword', 'application/vnd.ms-office'),
    'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
];

Step 4: Create Blade/HTML File

At last, we need to create a file-upload.blade.php file in the views folder and in this file, we will add the file upload Form HTML.

<!DOCTYPE html>
<html>
   <head>
      <title>Laravel File Upload Form - ScratchCode.io</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container">
         <div class="panel panel-primary">
            <div class="panel-heading">
               <h2>Laravel File Upload Form- ScratchCode.io</h2>
            </div>
            <div class="panel-body">
               @if ($message = Session::get('success'))
	               <div class="alert alert-success alert-block">
	                  <button type="button" class="close" data-dismiss="alert">×</button>
	                  <strong>{{ $message }}</strong>
	               </div>
               @endif

               @if (count($errors) > 0)
               <div class="alert alert-danger">
                  <strong>Whoops!</strong> There were some problems with your input.
                  <ul>
                     @foreach ($errors->all() as $error)
                     <li>{{ $error }}</li>
                     @endforeach
                  </ul>
               </div>
               @endif

               <form action="{{ route('store.file') }}" method="POST" enctype="multipart/form-data">
                  @csrf
                  <div class="row">
                     <div class="col-md-6">
                        <input type="file" name="file" class="form-control"/>
                     </div>
                     <div class="col-md-6">
                        <button type="submit" class="btn btn-success">Upload File...</button>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>

Step 5: Output

Hurray! We have completed all steps for the Laravel file upload form. Let’s run the below command and see how it’s working.

php artisan serve

After running the above command, open your browser and visit the site below URL:

http://localhost:8000/file-upload
laravel file upload form tutorial with example
laravel file upload form tutorial with example success message

Notes: You can find the uploaded file in \storage\app\public\uploads the directory. Please note that the storage public folder is publicly available so if you want to keep files private then use the “local” disk driver like Storage::disk('public')

uploaded file in laravel file upload tutorial output

Additionally, read our guide:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. Redirect By JavaScript With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you to learn the Laravel file upload form tutorial with the example.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment