How to Upload Multiple File using Ajax in Laravel 9?

Published On: 15/06/2022 | Category: Laravel Laravel 9

Hi Dev,

This article will provide example of How to Upload Multiple File using Ajax in Laravel 9?. Here you will learn Laravel 9 Multiple File Upload using jQuery Ajax. you will learn Multiple File Upload using Ajax in Laravel 9. you will learn Upload multiple File without using form submit in laravel 9 with Ajax.

Let's see bellow example Upload multiple files jQuery Ajax in laravel 9.

This article will give you simple Laravel 9 Multiple File Upload using Ajax example

Let's start following example:

Step 1: Install Laravel

First of all we are going from scratch new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2 : Create New Migration

create migration table using Laravel 9 php artisan command, so first fire bellow command:

php artisan make:migration create_files_table
database/migrations/create_files_table.php
<?php

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

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

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

now, we need to run migration command to create database table:

php artisan migrate
Step 3 : Create New Model

Here, we already have table created, so we need create model run command to create model:

php artisan make:model File
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 = [
        'file',
    ];
}
Step 4 : Create Routes routes/web.php
<?php

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

/*
|--------------------------------------------------------------------------
| 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('/Multiple-File',[MultipleFileUploadAjaxController::class, 'index']);
Route::post('Multiple-File-Upload',[MultipleFileUploadAjaxController::class, 'store'])->name('file.store');
Step 5 : Create New Controller

In this second step, we need to create a new MultipleFileUploadAjaxController; in this file, we will add two method index() and store() for render view and store image logic.

Let's create MultipleFileUploadAjaxController by following command:

php artisan make:controller MultipleFileUploadAjaxController
app/Http/Controllers/MultipleFileUploadController.php
<?php

namespace App\Http\Controllers;

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

class MultipleFileUploadAjaxController extends Controller
{

    /**
     * Write Your Code..
     *
     * @return string
    */
    public function index()
    {
        return view('index');
    }

    /**
     * Write Your Code..
     *
     * @return string
    */
    public function store(Request $request)
    {
        $request->validate([
            'files' => 'required',
            'files.*' => 'required|mimes:pdf,csv,txt,xlx,xls|max:2048',
        ]);

        if ($request->hasFile('files')){
            
            $files = $request->file('files');
            foreach($files as $file)
            {   
                $fileName = $file->getClientOriginalName();  
                $file->move(public_path('files'), $fileName);

                $files[]['name'] = $fileName;
                File::create([
                    'file' => $fileName
                  ]);
            }
        }

        return response()->json(['message' => 'Files uploaded successfully']);
    }
}
Step 6: Create Blade File resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>How to Upload Multiple File using Ajax in Laravel 9?</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="text-center">How to Upload Multiple File using Ajax in Laravel 9? - Tuts-Station.com</h5>
                    </div>
                    <div class="card-body">

                         <div class="alert alert-success alert-dismissible fade show" style="display:none;" role="alert">
                            <div id="result"></div>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div> 

                        <form action="javascript:void(0)" method="POST" id="laravel-ajax-files-upload" enctype="multipart/form-data">
                            @csrf
                            <div class="mt-3">
                                <label>Select Files : <span class="text-danger">*</span></label>
                                <input type="file" name="files[]" class="form-control @error('files') is-invalid @enderror" multiple>
                                
                                <div>
                                    <span class="text-danger" id="error"></span>
                                </div>
                            </div>
                            <div class="text-center mt-3">
                                <button type="submit" class="btn btn-success" id="laravel-ajax-files-upload">Submit</button>
                            </div>
                            </div>     
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script type="text/javascript">
$(document).ready(function (e) {
    
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    /*------------------------------------------
    --------------------------------------------
    images Upload
    --------------------------------------------
    --------------------------------------------*/
    $('#laravel-ajax-files-upload').submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            type:'POST',
            url: "{{ route('ajaxFile.store')}}",
            data: formData,
            cache:false,
            contentType: false,
            processData: false,
            success: (data) => {
                this.reset();
                console.log(data);
                
                $('.alert').css('display','block');
                $('#result').text(data.message);
                
                setTimeout(() => {
                    $(".alert").remove();
                }, 3000);
            },
            error: function(data){
                console.log(data);
                $('#error').text(data.responseJSON.message);
            }
        });
    });
});
</script>
</body>
</html>
Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve
Output :

I hope it can help you...