Laravel 10 jQuery Ajax File Upload Progress Bar Tutorial

Last Updated on by in Laravel

Laravel File Upload and Progress Bar tutorial; In this step-by-step guide, we will teach you how to create a file upload and progress bar component in the Laravel application using jQuery Ajax.

File upload is a quintessential component in every web/mobile application; it lets you upload files such as images, document files, etc., to the server or database.

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.

In this Laravel progress bar tutorial, we will use Ajax to make an asynchronous HTTP request, and It primarily helps send and retrieve the data from a server.

The good thing about AJAX is if you make any request, you don’t have to refresh or reload the page, and it does all the work without halting the current process.

Ajax stands for Asynchronous JavaScript And XML; it is used to create dynamic and user-friendly web pages. Generally, it is a set of web development techniques utilizing many web technologies on the client-side to create asynchronous web applications.

Laravel 10 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 File Upload Progress Bar
  • Step 7: Start Laravel App

Download Laravel App

We assume you have already installed the PHP and Composer on 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

The database settings are kept inside the .env configuration files. To make the connection between laravel and the database, add the given code in the 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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

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

Configure Model and Migration

Next, we will create Model and Migrations; these files eloquently hold the database schema of the laravel application.

Now, type the given command to create model and migrations files.

php artisan make:model FileUpload -m

Get into the app/Models/FileUpload.php and place 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 the schema value inside the pre-defined Schema object inside the 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 propel the new table into the database.

php artisan migrate

Create and Set Up Controller

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

Create a new controller using the following composer command.

php artisan make:controller ProgressBarController

Now, we are ready to define the functions to view and handle the 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 in the routes/web.php file; these 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 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 resources/views/welcome.blade.php file.

<!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; now, start the laravel application using the below composer command.

php artisan serve
http://127.0.0.1:8000/home

Laravel Progress Bar File Upload

Conclusion

We have successfully integrated the progress bar in the laravel application.

This tutorial briefly explained AJAX usage in laravel and comprehensively described how to upload a file and display the progress of uploading the file using the laravel progress bar.