Laravel 8 Ajax Multiple File Upload Tutorial

Laravel 8 multiple file upload ajax with validation. In this post, i will share with you how to upload multiple file using jQuery ajax in laravel 8 with validation. And save multiple files into database and public storage directory (folder).

In this post, the jQuery and ajax code will upload multiple file into database and folder in laravel 8 without reload or refresh page.

In this post, i will help you to build multiple file upload using jQuery and ajax with validation in laravel 8 app.

Laravel 8 multiple file upload using jQuery ajax validation app will look like in below image:

  • Multiple file upload using ajax in laravel 8
  • If any error occure while uploading multiple files
  • After successfully multiple file uploaded in laravel 8

Multiple File Upload Using Ajax in Laravel 8 With Validation

Simple steps to uploading multiple file in laravel 8 app:

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Configuring Database Details
  • Step 3 – Create Model & Migration
  • Step 4 -Create Ajax Upload Routes
  • Step 5 – Creating Ajax Upload Controller
  • Step 6 – Create Blade View
    • Create ajax multiple file upload form
    • Implement Ajax Code For Multiple File Upload
    • Implement Validation jQuery Code
  • Step 7 – Start Development Server
  • Step 8 – Run This App On Browser

Step 1 – Install Laravel 8 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 8 latest application using the following command:

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

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like 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 – Create Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaraAjaxFilesUpload

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 8 multiple file upload tutorial app, which is located inside the following locations:

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

So, find create_files_table.php file inside LaravelFileUpload/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 Upload Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\AjaxMultipleFileUploadController;

Route::get('ajax-files-upload', [AjaxMultipleFileUploadController::class, 'index']);

Route::post('ajax-files-upload', [AjaxMultipleFileUploadController::class, 'store']);

Step 5 – Creating Ajax Upload Controller

In step 5, create multiple file upload ajax controller by using the following command:

php artisan make:controller AjaxMultipleFileUploadController

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

The following laravel validation rules will validate file before upload/save into database:

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

So open AjaxMultipleFileUploadController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\File;

class AjaxMultipleFileUploadController extends Controller
{
    public function index()
    {
        return view('ajax-files-upload');
    }


    public function store(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]['store_path'] = $path;
		        }
		   }

		    File::insert($insert);

		    return response()->json(['success'=>'Multiple FIle has been uploaded using ajax into db and storage directory']);

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

	}
}

The following single line of code will upload files inside storage/app/public/files directory:

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

Step 6 – Create Blade View

In step 6, create new blade view file that named ajax-files-upload.blade.php inside resources/views directory for multiple file upload ajax form.

  • Create ajax multiple file upload form

Then create multiple file upload ajax form on this ajax-files-upload.blade.php file:

        <form id="ajax-multiple-file-upload" 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">
                        <div class="input-group">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
                        </div>
                        <div class="custom-file">
                          <input type="file" class="custom-file-input" id="files" name="files[]" multiple="">
                          <label class="custom-file-label" for="inputGroupFile01">Choose Multiple Files</label>
                        </div>
                      </div>
                    </div>
                </div>                
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>
  • Implement Ajax Code For Multiple File Upload

The following jQuery and ajax code will upload multiple file in laravel 8:

   $('#ajax-multiple-file-upload').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('ajax-files-upload')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: (data) => {
           this.reset();
           alert('Multiple File has been uploaded using jQuery ajax');
        },
        error: function(data){
           alert(data.responseJSON.errors.files[0]);
         }
       });
   });
  • Implement Validation jQuery Code

The following code display error message in laravel file upload forms. So do not forget to add the following code along laravel forms fields:

        error: function(data){
           alert(data.responseJSON.errors.files[0]);
         }

Don’t worry i have already added all the above code in ajax-files-upload.blade.php.

So, you can add the following php and html form code into ajax-files-upload.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Ajax Multiple File Upload With Validation</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">

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Multiple File Upload Using Ajax In Laravel 8</h2>
    </div>

    <div class="card-body">
        <form id="ajax-multiple-file-upload" 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">
                        <div class="input-group">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
                        </div>
                        <div class="custom-file">
                          <input type="file" class="custom-file-input" id="files" name="files[]" multiple="">
                          <label class="custom-file-label" for="inputGroupFile01">Choose Multiple Files</label>
                        </div>
                      </div>
                    </div>
                </div>                
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>

</div>  
<script type="text/javascript">
     
$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
   
  
   $('#ajax-multiple-file-upload').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('ajax-files-upload')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: (data) => {
           this.reset();
           alert('Multiple File has been uploaded using jQuery ajax');
        },
        error: function(data){
           alert(data.responseJSON.errors.files[0]);
         }
       });
   });
});

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

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel 8 ajax multiple file upload application:

php artisan serve

Step 8 – Run This App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/ajax-files-upload

Note that, in this example, the file will be upload on the following path – storage/app/public/files.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *