Wednesday, July 3, 2024
HomeLanguagesAjaxLaravel 10 Ajax Multiple File Upload Tutorial

Laravel 10 Ajax Multiple File Upload Tutorial

If you use Ajax to upload multiple files in the Laravel web application. So you can use it to save multiple files in the Laravel application’s directory and MySQL database with Ajax without refreshing the whole page.

So, in this tutorial, you will learn how to upload multiple files in Laravel 10 web application using jquery ajax without refreshing the whole page.

How to Upload Multiple File using Ajax in Laravel 10

By using the following steps, you can upload multiple file using ajax in Laravel 10 applications:

  • Step 1 – Setup New Laravel 10 Project
  • Step 2 – Setup Database with Laravel Project
  • Step 3 – Create File For Model & Migration
  • Step 4 – Define 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 – Setup New Laravel 10 Project

First of all, start your terminal to download or install Laravel 10 new setup. Run the following commands in it to install the new Laravel 10 app on your system:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install Laravel 10 latest application using the following command:

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

Step 2 – Setup Database with Laravel Project

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

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 File For Model & Migration

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

First of all, navigate to 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 10 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 – Define 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 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 into 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 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 text editor and update the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 10 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 10</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 10:

<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 Posts

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments