In this tutorial you will learn about the Laravel 8 Ajax Multiple Image Upload Tutorial and its application with practical example.
In this Laravel 8 Ajax Multiple Image Upload Tutorial, we will learn how to upload multiple image using ajax along with validation in laravel 8. In this Ajax Multiple Image Upload Tutorial, I’ll show you how to upload multiple image using ajax in laravel and save 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.
Laravel 8 Ajax Multiple Image Upload with Preview Tutorial
In this I’ll show you how to upload multiple image using jQuery and ajax in laravel 8. While uploading image using ajax we will display with preview. In this step by step tutorial I’ll demonstrate example of multiple image using ajax in laravel 8. Please follow the step given below:
- Install Laravel 8 Application
- Database Configuration
- Build Photo Model & Migration
- Create Routes
- Generate Controller using Artisan Command
- Create an Ajax Form to Upload Multiple Image
- jQuery Code To Show Multiple Image Preview
- Write Ajax Code to Upload Multiple Image
- Start Development Server
Install Laravel 8
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 lara8blog |
Configure Database In .env file
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.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=lara8blog DB_USERNAME=root DB_PASSWORD= |
Create Model & Migration
Now, we have to define table schema for photos table. Open terminal and let’s run the following command to generate a migration along with model file to create photos table in our database.
1 |
php artisan make:model Photo -m |
Once this command is executed you will find a migration file created under “database/migrations”. lets open migration file and put following code in it –
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('photos', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('path'); $table->timestamps(); }); } |
Now, run following command to migrate database schema.
1 |
php artisan migrate |
After, the migration executed successfully the photos table will be created in database.
Create Routes
After this, we need to add following routes in “routes/web.php” file along with a resource route. Lets open “routes/web.php” file and add following route.
routes/web.php
1 2 3 4 5 |
use App\Http\Controllers\AjaxUploadMultipleImageController; Route::get('multiple-image-preview', [AjaxUploadMultipleImageController::class, 'index']); Route::post('upload-multiple-image-ajax', [AjaxUploadMultipleImageController::class, 'saveUpload']); |
Create Controller By Artisan Command
Now, lets create a controller for ajax multiple image uploading. Create a controller named AjaxUploadMultipleImageController using command given below –
1 |
php artisan make:controller AjaxUploadMultipleImageController |
Once the above command executed, it will create a controller file AjaxUploadMultipleImageController.php in app/Http/Controllers/ directory. Open the AjaxUploadMultipleImageController.php file and put the following code in it.
app/Http/Controllers/AjaxUploadMultipleImageController.php
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\Photo; class AjaxUploadMultipleImageController extends Controller { public function index() { return view('multiple-image-upload-preview-ajax'); } public function saveUpload(Request $request) { $validatedData = $request->validate([ 'images' => 'required', 'images.*' => 'mimes:jpg,png,jpeg,gif,svg' ]); if($request->TotalImages > 0) { for ($x = 0; $x < $request->TotalImages; $x++) { if ($request->hasFile('images'.$x)) { $file = $request->file('images'.$x); $path = $file->store('public/images'); $name = $file->getClientOriginalName(); $insert[$x]['name'] = $name; $insert[$x]['path'] = $path; } } Photo::insert($insert); return response()->json(['success'=>'Multiple Image has been uploaded into db and storage directory']); } else { return response()->json(["message" => "Please try again."]); } } } |
Create an Ajax Form to Upload Multiple Image
In this step, we will create view/blade file to generate and display ajax multiple Image Upload Form. Lets create a blade file “multiple-image-upload-preview-ajax.blade.php” in “resources/views/” directory and put the following code in it respectively.
resources/views/multiple-image-upload-preview-ajax.blade.php
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
<!DOCTYPE html> <html> <head> <title>Laravel 8 Multiple Image Upload AJAX With Preview</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> <style> .show-multiple-image-preview img { padding: 6px; max-width: 100px; } </style> </head> <body> <div class="container mt-5"> <h2 class="text-center">Laravel 8 Ajax Multiple Image Upload With Preview</h2> <div class="text-center"> <form id="multiple-image-preview-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="images[]" id="images" placeholder="Choose images" multiple > </div> @error('images') <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div> @enderror </div> <div class="col-md-12"> <div class="mt-1 text-center"> <div class="show-multiple-image-preview"> </div> </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') } }); $(function() { // Multiple images preview with JavaScript var ShowMultipleImagePreview = function(input, imgPreviewPlaceholder) { if (input.files) { var filesAmount = input.files.length; for (i = 0; i < filesAmount; i++) { var reader = new FileReader(); reader.onload = function(event) { $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder); } reader.readAsDataURL(input.files[i]); } } }; $('#images').on('change', function() { ShowMultipleImagePreview(this, 'div.show-multiple-image-preview'); }); }); $('#multiple-image-preview-ajax').submit(function(e) { e.preventDefault(); var formData = new FormData(this); let TotalImages = $('#images')[0].files.length; //Total Images let images = $('#images')[0]; for (let i = 0; i < TotalImages; i++) { formData.append('images' + i, images.files[i]); } formData.append('TotalImages', TotalImages); $.ajax({ type:'POST', url: "{{ url('upload-multiple-image-ajax')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { this.reset(); alert('Images has been uploaded using jQuery ajax with preview'); $('.show-multiple-image-preview').html("") }, error: function(data){ console.log(data); } }); }); }); </script> </body> </html> |
Create Images Directory inside Storage/app/public
Before uploading any file make sure you have created following directory in the storage/app/public folder called images
.
1 |
$path = $request->file('image')->store('public/images'); |
Run 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://localhost:8000/multiple-image-preview |