CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

23 February, 2021

Laravel 8 Ajax Multiple Image Upload Tutorial

 Programing Coderfunda     February 23, 2021     Laravel, laravel-tutorial     No comments   

 Laravel 8 Ajax Multiple Image Upload Tutorial


 

Ajax multiple image uploading with preview in laravel 8 app. In this tutorial, we would like to share with you how to upload multiple image using ajax with preview in laravel 8 app.

Before uploading multiple images using jQuery and ajax into DB and folder in laravel 8 app, will display the preview of multiple images using jQuery. And Also, validate image mime type, size, height, width on the server side.

Multiple image upload using ajax in laravel 8 app is very basic requirement of every laravel project.

So, In this tutorial, you will learn how to upload multiple image using jQuery and ajax with preview in laravel 8 App.

Laravel 8 Ajax Multiple Image Upload with Preview Tutorial

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Database Configuration
  • Step 3 – Build Photo Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Generate Controller using Artisan Command
  • Step 6 – Create an Ajax Form to Upload Multiple Image
  • Step 7 – jQuery Code To Show Multiple Image Preview
  • Step 8 – Write Ajax Code to Upload Multiple Image
  • Step 9 – Start Development Server

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 blog

Step 2 – Database Configuration

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

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 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 Photo -m

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

  • blog/app/Models/Photo.php
  • blog/database/migrations/create_photos_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:

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, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

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

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']);

Step 5 – Create 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:

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."]);
        }
 
    }  
         
}

Step 6 – Create an Ajax Form to Upload Multiple Image

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

So, open this multiple-image-upload-preview-ajax.blade.php file in text editor and update 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
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 - 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>
<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 - Tutsmake.com</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>

Step 7 – jQuery Code To Show Multiple Image Preview

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(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');
});
});

Step 8 – Write Ajax Code to Upload Multiple Image

In this step, implement the jQuery and ajax code will upload multiple image on laravel 8 controller 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
$('#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);
}
});
});

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/multiple-image-preview

 

  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Laravel 8 Ajax Image Upload with Preview TutorialLaravel 8 Ajax Image Upload with Preview Tutorial Laravel 8 ajax image upload with preview example. In this tutorial, we will share with you how … Read More
  • Laravel 8 Ajax Multiple Image Upload Tutorial Laravel 8 Ajax Multiple Image Upload Tutorial Ajax multiple image uploading with preview in laravel 8 app. In this tutorial, we would like … Read More
  • Laravel 8 FullCalendar Ajax Tutorial Example Laravel 8 FullCalendar Ajax Tutorial Example Laravel 8 integrate fullcalendar using ajax tutorial. In this tutorial, you will learn how to … Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Features CodeIgniter
    Features CodeIgniter There is a great demand for the CodeIgniter framework in PHP developers because of its features and multiple advan...
  • Laravel Breeze with PrimeVue v4
    This is an follow up to my previous post about a "starter kit" I created with Laravel and PrimeVue components. The project has b...
  • Fast Excel Package for Laravel
      Fast Excel is a Laravel package for importing and exporting spreadsheets. It provides an elegant wrapper around Spout —a PHP package to ...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Manipulate Image URLs in Laravel with the Image Transform Package - 6/19/2025
  • Handle Nested Arrays Elegantly with Laravel's fluent() Helper - 6/18/2025
  • Laravel 12.19 Adds a useEloquentBuilder Attribute, a FailOnException Queue Middleware, and More - 6/18/2025
  • Test Deferred Operations Easily with Laravel's withoutDefer Helper - 6/18/2025
  • Larallow is a Permissions Package With Support for Scopes - 6/17/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda