How To Implement File Upload Progress Bar Using JQuery Ajax In Laravel 9 Tutorial

Laravel 9 File Upload and Progress Bar tutorial. In this step-by-step guide, let’s learn how to upload a file with a progress bar in Laravel using jQuery Ajax.

Uploading a file is a standard component in every web/mobile application. We can upload different types of files like images, document files, or more to the server or database.

The file upload module can be more relevant and user-friendly with a progress bar attached to it. It notifies us about file uploading progress.

Let’s have a look at this progress bar tutorial, where we will use Ajax to make asynchronous HTTP requests. This will primarily help to send and receive data from the server.

The quality of AJAX is, while making requests, you don’t need to refresh or reload a page. It does all the work without stopping the current process.

AJAX is abbreviated for Asynchronous JavaScript And XML, and is used to create dynamic and user-friendly web pages. Generally, it is a set of web development techniques which we can use many web technologies on the client-side to create asynchronous web applications.

Laravel 9 Ajax File Upload Progress Bar Example

  • Step 1: Download Laravel App
  • Step 2: Connect to Database
  • Step 3: Configure Model and Migration
  • Step 4: Create and Set Up Controller
  • Step 5: Create Routes
  • Step 6: Add AJAX Progress Bar
  • Step 7: Start Laravel App

Download Laravel App

We assume you already have PHP and Composer installed in your system. If yes, then go ahead and create a new Laravel application using the given composer command.

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

Next, step inside the project.

cd laravel-demo

Connect to Database

Database settings are added inside the .env configuration files. They help create a connection between Laravel and the database. Add the code given below in your .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

In case you are using MAMP local server in macOS, assure to append UNIX_SOCKET and DB_SOCKET database credentials in .env file as shown below.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Configure Model and Migration

Next, we will create a Model and some Migrations, these files eloquently hold the database schema of a Laravel application.

Add and execute the given command to create model and migrations files.

php artisan make:model FileUpload -m

Open the app/Models/FileUpload.php file and add the following code.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class FileUpload extends Model
{
    use HasFactory;
    protected $fillable = [
        'name'
    ];    
}

Further, define a schema value inside the pre-defined Schema object in your database/migrations/create_file_uploads_table.php file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFileUploadsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('file_uploads', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('file_uploads');
    }
}

After updating models and migrations config files, run the migration to send the new table into the database.

php artisan migrate

Create and Set Up Controller

A controller is a single class in where you can add multiple methods and functions to perform a specific task through request.

You can create a new controller using the composer command below.

php artisan make:controller ProgressBarController

Now, we are ready to define the functions to view and handle a post request for progress bar file upload in Laravel.

So, add the code in app/Http/Controllers/ProgressBarController.php file.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FileUpload;
class ProgressBarController extends Controller
{
    public function index()
    {
        return view('welcome');
    }
 
    public function uploadToServer(Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);
 
       $name = time().'.'.request()->file->getClientOriginalExtension();
  
       $request->file->move(public_path('uploads'), $name);
 
       $file = new FileUpload;
       $file->name = $name;
       $file->save();
  
        return response()->json(['success'=>'Successfully uploaded.']);
    }
}

Create Routes

Next, add the two routes given below in the routes/web.php file. The route methods help you make GET and POST requests.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProgressBarController;
/*
|--------------------------------------------------------------------------
| 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('/home', [ProgressBarController::class, 'index']);
Route::post('/upload-doc-file', [ProgressBarController::class, 'uploadToServer']);

Integrate AJAX Progress Bar in Laravel

Now, we can create a file to upload component and add a progress bar to display the progress of events that use jQuery AJAX.

To design the UI for the file upload and progress bar, we can use Bootstrap 5 and jQuery, so open your resources/views/welcome.blade.php file, and add the code shown below.

<!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>  
        <form id="fileUploadForm" method="POST" action="{{ url('/upload-doc-file') }}" 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>
            <div class="form-group">
                <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>
    </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>
        $(function () {
            $(document).ready(function () {
                $('#fileUploadForm').ajaxForm({
                    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');
                    }
                });
            });
        });
    </script>
</body>
</html>

Start Laravel App

We have integrated the jQuery file upload percentage progress bar in Laravel. Start your Laravel application using the composer command shown below.

php artisan serve
http://127.0.0.1:8000/home
Laravel Progress Bar File Upload

Conclusion

The tutorial helps you to successfully integrate a progress bar in your Laravel application.

It briefly explains use of AJAX in Laravel and comprehensively describes how to upload a file and display the progress of file uploading using a Laravel progress bar.