Like a single image upload, you can upload multiple images using Ajax in Laravel 9. Everything will be quite similar. The main thing is to handle the images in the form of an array. Also, you will need to add an attribute named multiple in the input type file. While sending the Ajax request, you will need to segregate the array of images. Then we will append images one by one to the form data. So, in this post, we are going to achieve the below results.
We will be having the image required validation.
After selecting the image(s) you can trigger the upload.
On the success upload result, you will get the below response.
So, we will be covering up these functionalities. Let’s dive into the post.
How to Upload Image Using Ajax in Laravel 9 with Validation
Create Project to Upload Multiple Images Using Ajax
If you already have a project setup then it is not recommended to create a new one.
composer create-project --prefer-dist laravel/laravel ajax-images-upload
After creating the project, you need to configure the database for it.
How to Create a CRUD Application Using Ajax in Laravel 9
Create and Configure Database
For database configuration, create a database. Now, configure the project by adding the database credentials in the .env file of the project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
Next, create a model, migration, and a controller for uploading multiple images using Ajax.
How to Upload Multiple Files in Laravel 9 with Validation
Create Model, Migration, and Controller For Multiple Images Upload
You can create these three files in the same command.
php artisan make:model Image -mc
Once, you created the files, let’s start by adding the migration for the table.
How to Upload File in Laravel 9 With Validation
Add Migration For Images Table
Find the created migration file and add the below schema.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('imageName');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
};
After that, you will have to migrate the schema. So, hit the below command.
php artisan migrate
On migration, it will dump the table. Next, you will have to add the fillable property in its corresponding modal.
Add Fillable Property in Modal
Navigate to the Image modal and add the below snippet.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'imageName'
];
}
Next, move to the functionality implementation of Multiple images upload using Ajax.
Add Functionality of Multiple Images Upload
Open the ImageController.php and add the below functions.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Return image upload view
* @param request
* @return response
*/
public function index() {
return view('upload');
}
/**
* Upload image
* @param request
* @return response
*/
public function upload(Request $request) {
$request->validate([
'images' => 'required',
'images.*' => 'mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$data = [];
if ($request->hasfile('images')) {
foreach ($request->images as $image) {
$name = time().rand(1,100).'.'.$image->extension();
if ($image->move(public_path('uploads'), $name)) {
$data[] = Image::create(["imageName" => $name]);
}
}
}
if ($data) {
return response()->json(['status' => 'success', 'data' => $data, 'message' => 'Success! image(s) uploaded']);
}
else {
return response()->json(['status' => 'failed', 'data' => $data, 'message' => 'Failed! image(s) not uploaded']);
}
}
}
Add routes respectively.
Add Routes For Multiple Images Upload
For adding the routes, open the web.php file and add the below routes.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'index'])->name('image');
Route::post('image', [ImageController::class, 'upload'])->name('image');
Last but not least, you have to create a view.
How to Upload Image in Laravel 9 with Validation
Create a View For Multiple Images Upload
Navigate to the views folder and create a new blade file with the name upload.blade.php. Now, add the below snippets.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 9 Multiple Image Upload Using Ajax - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<meta name="csrf-token" content="{{ csrf_token() }}"/>
<style>
.error {
color: red;
}
</style>
</head>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-7 col-md-7 col-sm-12 m-auto">
<div id="result"></div>
<form id="uploadForm" method="POST" enctype="multipart/form-data">
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 9 Multiple Images Upload Using Ajax </h4>
</div>
<div class="card-body">
<label for="file"> Image(s) <span class="text-danger">*</span> </label>
<input type="file" name="images[]" id="images" multiple class="form-control">
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js" integrity="sha512-37T7leoNS06R80c8Ulq7cdCDU5MNQBwlYoy1TX/WUsLFC2eYNqtKlV0QjH7r8JpG/S0GUMZwebnVFLPd6SU5yg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#uploadForm").validate({
rules: {
'images[]': {
required: true,
}
},
messages: {
'images[]': {
required: "Please upload the image(s)",
}
},
submitHandler: function(form, event) {
event.preventDefault();
let formData = new FormData(form);
const totalImages = $("#images")[0].files.length;
let images = $("#images")[0];
for (let i = 0; i < totalImages; i++) {
formData.append('images' + i, images.files[i]);
}
formData.append('totalImages', totalImages);
console.log(formData);
$.ajax({
url: "{{ route('image') }}",
type: 'POST',
data: formData,
processData: false,
cache: false,
contentType: false,
success: function(response) {
form.reset();
if (response && response.status === 'success') {
$("#result").append(`<div class='alert alert-success alert-dismissible fade show' role='alert'>${response.message}<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button></div>`);
setTimeout(() => {
$(".alert").remove();
}, 5000);
}
else if(response.status === 'failed') {
$("#result").append(`<div class='alert alert-success alert-dismisisble fade show' role='alert'>${response.message}<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button></div>`);
setTimeout(() => {
$(".alert").remove();
}, 5000);
}
}
});
}
});
});
</script>
</body>
</html>
That’s it for the functionality. Now, run the application and navigate to the route to check the result.
Conclusion
We covered multiple images upload functionality using Ajax in Laravel 9. We segregated images and passed them one by one image to form data. Through the form data, we extracted the array of images in Laravel 9 and uploaded it. That’s it for this post.
Leave a Reply