Laravel 8 — How to Upload File with Validations?

In this blog post, we’ll discuss about how to upload file in Laravel 9 with proper validations. I’ll show you step by step on how to upload a file with Laravel 8. This tutorial will help you to understand file uploading process from scratch.

In this example, we’ll be using two routes, one controller to upload a File from front to Laravel directory. One is GET route to display form and another one is POST route to submit file details to controller. On the GET route, we’ll use simple input type file where you can select file and upon submitting button it will send POST request to our another route.

Let’s get started, just follow below simple steps to understand the process. I’ll also put code and screenshot wherever necessary to understand the flow.

1. Install Laravel 8

Fresh copy of Laravel is needed before we start as we don’t want to disturb our existing projects. So, use below commands to install Laravel version 8 from scratch:

composer create-project ––prefer-dist laravel/laravel laravel-file-upload

It will take few seconds to minutes based on your internet connection. Once this is done, we’ll move to next step which is creating Routes.

2. Prepare Routes

As we discussed above, we’ll need to create two routes in our web.php file:

  1. GET /upload-file — This route will used to display upload form
  2. POST /upload-file — This route will send submitted file data to our controller for further processing

So now, go to your installation directory laravel-file-upload and find web.php file inside routes folder. You’ll see one index route already created there for you. Get rid of current content and paste following content into web.php file:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('upload-file', [UploadController::class, 'uploadForm'])->name('upload.form');
Route::post('upload-file', [UploadController::class, 'submitFile'])->name('submit.file');

In above code, we have added two routes and assigned functions to those two routes. Next is to create Controller file where we are going to write application logic.

3. Create Controller — UploadController

In this step, we will create new file UploadController.php inside app/Http/Controllers directory. In web.php, we have assigned two functions uploadForm and submitFIle. We need to create those two functions in this controller.

app/Http/Controllers/UploadController.php

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UploadController extends Controller
{
    /**
     * Display a upload form.
     */
    public function uploadForm()
    {
        return view('upload');
    }
  
    /**
     * Process incoming file from frontend and upload it.
     */
    public function submitFile(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:pdf|max:2048',
        ]);
  
        $fileName = time().'.'.$request->file->extension();  
   
        $request->file->move(public_path('uploads'), $fileName);
   
        return back()
            ->with('success','You have successfully upload file.')
            ->with('file',$fileName);
   
    }
}

We’ve successfully created routes and controller. Now, we need to include this controller into routes file. So here’s your final route file would look like:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UploadController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('upload-file', [UploadController::class, 'uploadForm'])->name('upload.form');
Route::post('upload-file', [UploadController::class, 'submitFile'])->name('submit.file');

Now, let’s move to front part where we need to create blade file to display form.

4. Create Blade File

In this step, we’ll create upload.blade.php file which will renders form with input type file and submit button

resources/views/upload.blade.php

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 8 -- File Upload Example by CodePortal</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
    </head>

    <body>
        <div class="container">
            <div class="panel panel-primary">
                <div class="panel-heading"><h2>Laravel 8 -- File Upload Example by CodePortal</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('submit.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</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

Now, we’re good to go.

5. Test File Upload

To test our work, go to root directory of our project and open command line. In command line run following command:

php artisan serve

This will start our Laravel application and serves it on 8000 port like this:

You can access it via going to http://localhost:8000/upload-file:

If you can see output as above then you’ve successfully learned and setup File Upload with Laravel 8.

You can also find whole code over here — https://github.com/harshdoshi999/laravel-8-file-upload

2 thoughts on “Laravel 8 — How to Upload File with Validations?

Leave a Reply

Your email address will not be published.

six + 4 =