Laravel 9 Ajax File Upload with Progress Bar Example

Laravel 9 Ajax File Upload with Progress Bar Example; In this step by step tutorial you will learn how to upload file with progress bar and percentage component in the Laravel application using jquery Ajax.

Uploading with a normal size file we don’t need to show anything but when you have a large amount of file size then it takes time to upload on a server. Maybe you can’t reduce time to upload file or image, but you can display a progress bar with a percentage, so the client can understand how much is remaining to upload a file.

A file upload module becomes more relevant and user-friendly when a progress bar is attached to it; it helps to know about file uploading progress. The laravel image or file upload with progress bar will be implemented in laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 apps.

Laravel File Upload with Progress Bar Example

Follow to the following steps to implement file upload progress bar with percentage using javascript funcationality in laravel 9 app:

  • Step 1: Install Laravel App
  • Step 2: Create Database & Connect to App
  • Step 3: Generate Model and Run Migration
  • Step 4: Make Routes
  • Step 5: Create Controller
  • Step 6: Integrate AJAX Progress Bar in Laravel
  • Step 7: Run Development Server

Insall Laravel App

Open terminal further run below command to manifest a new laravel project, ignore this step if project is already installed:

composer create-project laravel/laravel laravel-file-upload-progress-bar

Go into the app:

cd laravel-file-upload-progress-bar

Create Database & Connect to App

This step explains how to make database connection by adding database name, username and password in .env config file of your project:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=#your database name
DB_USERNAME=#database username
DB_PASSWORD=#database password

Generate Model and Run Migration

Now generate model and migration file just adding the below command in your terminal which is generate a model file and migration which will show your database table after running the migration command.

php artisan make:model File -m

Here open your model file and update the fillable properties just like below.

app\Models\File.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;
    protected $fillable = ['name', 'path'];
}

Next, you can see in your database migration directory created a new file same as below, here you need to add you database columns.

database\migrations\2021_08_02_153718_create_files_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
}

After adding the columns now run the below command which is generate table in your database.

php artisan migrate

Make Routes

Open routes/web.php file and define the route to implement laravel ajax file upload with progress bar and percentage value;

<?php

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

Route::get('file-upload', [FileController::class, 'uploadFile']);
Route::post('file-upload', [FileController::class, 'storeFile'])->name('file.upload');

Create Controller

A controller is a single class in which you accumulate multiple methods and functions to perform a specific task through request.

Generate a new controller using the following composer command:

php artisan make:controller FileController

Next, optn the new generated controller file app\Http\Controllers\FileController.php and put the below code on it

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File;

class FileController extends Controller
{
    public function uploadFile()
    {

      return view('files');
    }

    public function storeFile(Request $request)
    {
        $request->validate([
          'file' => 'required',
        ]);

        if ($request->hasfile('files')) {
            $files = $request->file('files');

            foreach($files as $file) {
                $name = $file->getClientOriginalName();
                $path = $file->storeAs('uploads', $name, 'public');

                File::create([
                    'name' => $name,
                    'path' => '/storage/'.$path
                  ]);
            }
         }

        return response()->json(['success'=>'File successfully uploaded.']);
    }
}

Integrate AJAX Progress Bar in Laravel

Now, we will create a file uploading component and add a progress bar and display the progress of events using jQuery Ajax.

To design the file upload and progress bar, we will use Bootstrap 5 and jQuery, so open the files.blade.php file and put the following code on it.

resources\views\files.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel 8 Bootstrap 5 Progress Bar Example</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

    <div class="container mt-5" style="max-width: 500px">

        <div class="alert alert-warning mb-4 text-center">
           <h2 class="display-6">Laravel Dynamic Ajax Progress Bar Example</h2>
        </div>

        <div class="form-group mb-4">
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
            </div>
        </div>

        <form id="uploadFile" method="POST" action="{{ route('file.upload') }}" enctype="multipart/form-data">
            @csrf
            <div class="form-group mb-3">
                <input name="file" type="file" class="form-control">
            </div>

            <div class="d-grid mb-3">
                <input type="submit" value="Submit" class="btn btn-primary">
            </div>


        </form>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>

    <script>
        $(document).ready(function () {
            $('#uploadFile').ajaxForm({
                beforeSubmit: validate,
                beforeSend: function () {
                    var percentage = '0';
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentage = percentComplete;
                    $('.progress .progress-bar').css("width", percentage+'%', function() {
                      return $(this).attr("aria-valuenow", percentage) + "%";
                    })
                },
                complete: function (xhr) {
                    console.log('File has uploaded');
                }
            });
        });

        function validate(formData, jqForm, options) {
            var form = jqForm[0];
            if (!form.file.value) {
                alert('File not found');
                return false;
            }
        }
    </script>
</body>

</html>

Start Development Server

All things we have done for ajax jQuery file upload percentage progress bar in laravel. Now, start the laravel application using the below composer command.

php artisan serve

Open your browser and hit the below url.

http://127.0.0.1:8000/file-upload

We have successfully integrated the progress bar in the laravel application, and easily lean how to upload a file and display the progress of uploading the file using the laravel progress bar.

Leave a Comment