Thursday, December 26, 2024
Google search engine
HomeLanguagesLaravel 9 Multiple File Upload using jQuery Ajax

Laravel 9 Multiple File Upload using jQuery Ajax

Multiple file upload using ajax in laravel 9; In this tutorial, we will learn how to upload multiple file using jquery ajax in laravel 9 apps.

This multiple file upload using ajax in laravel tutorial will create ajax file upload form and write jQuery and code to upload multiple files into database and folder.

Multiple File Upload using Ajax in Laravel 9

Use the following steps to multiple file upload using ajax in laravel 9:

  • Step 1 – Install Laravel 9 Application
  • Step 2 – Configure Database with App
  • Step 3 – Build File Model & Migration
  • Step 4 – Create Ajax Multiple File Upload Routes
  • Step 5 – Make Controller using Artisan Command
  • Step 6 – Create an Ajax Form to Upload Multiple File
  • Step 7 – Ajax Code to Upload Multiple File
  • Step 8 – Start Development Server

Step 1 – Install Laravel 9 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

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

Step 2 – Configure Database with App

In step 2, open your downloaded laravel apps into any text editor. Then find .env file and configure database detail like the following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Build File Model & Migration

In this step, use the below-given command to create file migration and model file.

First of all, navigate to the project by using the following command:

cd / blog

Then create model and migration file by using the following command:

php artisan make:model File -m

The above command will create two files into your laravel multiple File upload with validation tutorial app, which is located inside the following locations:

  • blog/app/Models/File.php
  • blog/database/migrations/create_files_table.php

So, find create_photos_table.php file inside blog/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Ajax Multiple File Upload Routes

In this step, open your web.php file, so navigate inside routes directory. Then update the following routes into the web.php file:

use App\Http\Controllers\MultiFileUploadAjaxController;

Route::get('multi-file-ajax-upload', [MultiFileUploadAjaxController::class, 'index']);

Route::post('store-multi-file-ajax', [MultiFileUploadAjaxController::class, 'storeMultiFile']);

Step 5 – Make Controller using Artisan Command

In this step, use the below-given PHP artisan command to create a controller:

php artisan make:controller AjaxUploadMultipleImageController

The above command will create AjaxUploadMultipleImageController.php file, which is located inside blog/app/Http/Controllers/ directory.

So open UploadImagesController.php file and add the following code to it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\File;

class MultiFileUploadAjaxController extends Controller
{
    public function index()
    {
        return view('multi-file-ajax-upload');
    }


    public function storeMultiFile(Request $request)
    {
        
       $validatedData = $request->validate([
        'files' => 'required',
        'files.*' => 'mimes:csv,txt,xlx,xls,pdf'
        ]);

        if($request->TotalFiles > 0)
        {
               
           for ($x = 0; $x < $request->TotalFiles; $x++) 
           {

               if ($request->hasFile('files'.$x)) 
                {
                    $file      = $request->file('files'.$x);

                    $path = $file->store('public/files');
                    $name = $file->getClientOriginalName();

                    $insert[$x]['name'] = $name;
                    $insert[$x]['path'] = $path;
                }
           }

            File::insert($insert);

            return response()->json(['success'=>'Ajax Multiple fIle has been uploaded']);

         
        }
        else
        {
           return response()->json(["message" => "Please try again."]);
        }

    }
}

Step 6 – Create an Ajax Form to Upload Multiple File

In step, this, Go to the resources/views directory. And then create a new blade view file named multi-file-ajax-upload.blade.php inside this directory.

So, open this multi-file-ajax-upload.blade.php file in a text editor and update the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 9 Ajax Multiple File Upload - Tutsmake.com</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

   <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

</head>
<body>

<div class="container mt-5">


    <h2 class="text-center">Multiple File Upload Using Ajax In Laravel 9</h2>

    <div class="text-center">
        <form id="multi-file-upload-ajax" method="POST"  action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="files[]" id="files" placeholder="Choose files" multiple >
                    </div>
                </div>           
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

</div>  
<script type="text/javascript">
     
$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
   
  
   $('#multi-file-upload-ajax').submit(function(e) {

     e.preventDefault();
  
      var formData = new FormData(this);

      let TotalFiles = $('#files')[0].files.length; //Total files
      let files = $('#files')[0];
      for (let i = 0; i < TotalFiles; i++) {
          formData.append('files' + i, files.files[i]);
      }
      formData.append('TotalFiles', TotalFiles);
  
     $.ajax({
        type:'POST',
        url: "{{ url('store-multi-file-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: (data) => {
           this.reset();
           alert('Files has been uploaded using jQuery ajax');
        },
        error: function(data){
           alert(data.responseJSON.errors.files[0]);
           console.log(data.responseJSON.errors);
         }
       });
   });
});

</script>
</body>
</html>

Step 7 – Ajax Code to Upload Multiple File

In this step, implement the jQuery code to display or show multiple image preview before upload using ajax in laravel:

<script type="text/javascript">
     
$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
   
  
   $('#multi-file-upload-ajax').submit(function(e) {

     e.preventDefault();
  
      var formData = new FormData(this);

      let TotalFiles = $('#files')[0].files.length; //Total files
      let files = $('#files')[0];
      for (let i = 0; i < TotalFiles; i++) {
          formData.append('files' + i, files.files[i]);
      }
      formData.append('TotalFiles', TotalFiles);
  
     $.ajax({
        type:'POST',
        url: "{{ url('store-multi-file-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: (data) => {
           this.reset();
           alert('Files has been uploaded using jQuery ajax');
        },
        error: function(data){
           alert(data.responseJSON.errors.files[0]);
           console.log(data.responseJSON.errors);
         }
       });
   });
});

</script>

Step 9 – Start Development Server

In this step, run the following command on cmd to start the development server:

php artisan serve

Then start this app on browser, so open your browser and fire the following url into browser:

http://127.0.0.1:8000/multi-file-ajax-upload

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

RELATED ARTICLES

Most Popular

Recent Comments