In this tutorial you will learn about the Multiple File Upload using Ajax in Laravel 8 and its application with practical example.
In this Multiple File Upload using Ajax in Laravel 8 tutorial, I’ll show you how to upload multiple files using ajax in laravel 8. In this laravel 8 multiple file upload example, I’ll show you how to validate and upload multiple files into folder and then save it into database. In this tutorial before saving multiple image into database we will validate image and then save it into directory. Before uploading the image we will validate the image. After successfully uploading multiple images into the folder and saving it in database we will display success message on the screen.
- Multiple File Upload using Ajax in Laravel 8
- Step 1 – Install Laravel 8 Application
- Step 2 – Database Configuration
- 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 9 – Start Development Server
Multiple File Upload using Ajax in Laravel 8
In this step by step tutorial I’ll demonstrate how to upload multiple files using ajax in laravel 8 with validation. I’ll also show you how to upload multiple pdf, txt, csv, excel, doc files in laravel 8 application. Please follow the steps to upload multiple files in laravel 8 given below:
- Step 1 – Install Laravel 8 Application
- Step 2 – Database Configuration
- 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 8 Application
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2 – Database Configuration
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model File -m |
The above command will create two files:
- blog/app/Models/File.php
- blog/database/migrations/create_files_table.php
Open create_files_table.php file inside blog/database/migrations/ directory. Then open this file and add the following code into function up() on this file:
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('files', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('path'); $table->timestamps(); }); } |
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan migrate |
Step 4 – Create Ajax Multiple File Upload Routes
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 |
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
Now, lets create a controller named AjaxUploadMultipleImageController using command given below –
1 |
php artisan make:controller AjaxUploadMultipleImageController |
The above command will create AjaxUploadMultipleImageController.php file, which is located inside blog/app/Http/Controllers/ directory. Now, open UploadImagesController.php file and add the following code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<?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 we will create blade file. Go to resources/views directory. And then create a new blade view file named multi-file-ajax-upload.blade.php inside this directory. Open multi-file-ajax-upload.blade.php file and put the following code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<!DOCTYPE html> <html> <head> <title>Laravel 8 Ajax Multiple File Upload</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 8</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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<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
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://127.0.0.1:8000/multi-file-ajax-upload |