Image upload is a crucial aspect of web development. It’s important to ensure that your users can easily upload their images without any hassle. With Laravel 10, you can use AJAX to make the image upload process seamless and user-friendly. The image can be uploaded using Ajax in Laravel 10. The process of image uploading is different from a general form request. Laravel provides a simple and elegant way to handle image uploads using AJAX. In this post, I will be showing you how you can implement Ajax Image upload in Laravel 10. On the server side, we will be handling the image upload. Laravel provides a simple way to handle file uploads using the Request object.
Take a look at the below results that we are going to achieve by the end of this post.
There will be a file validation that will accept images only. Apart from the image, if you select any other file, then it will through an error as shown below.
However, if you select a correct file (image) then on success of upload, it will return success response.
The success response will be shown in the Alert box as shown below.
Now, let’s move on to the post for achieving the image upload result using Ajax.
How to Upload Multiple Images with Validation in Laravel 10
Prerequisites
We will be jumping directly on Ajax image upload in Laravel 10. So, I am assuming, you are ready and familiar with the basic setup of the Laravel 10 application.
If you don’t have a Laravel 10 application, then you may create a new one. However, in order to create a Laravel 10 project, you will be needing the below tools and configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Configure Database For Ajax Image Upload in Laravel 10
Firstly, you need to create a database in MySQL. Secondly, navigate to the project folder. Then look at .env file and add the DB configuration as shown below.
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 }}
After DB configuration you need to create a model and migration file.
Create a Model, Migration, and Controller
You can create a model, migration, and controller all in one single command. Therefore, you need to hit the below command in the terminal.
php artisan make:model Image -mc
After creating these files, firstly, you need to add the schema in the migration.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('image_name')->nullable();
$table->string('image_original_name')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('images');
}
};
After adding the schema in the migration file, you need to run the migrate command in order to dump the schema in the database.
php artisan migrate
Now, Let’s quickly add the mass assignment to the model.
How to Upload Image in Laravel 10 with Validation
Add Mass Assignment in the Model
For adding the mass assignment, just navigate to the model named Image.php 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 = [
'image_name',
'image_original_name',
];
}
Next, we will be working on the functionality part for image upload using Ajax.
Add Functionality For Image Upload Using Ajax
For adding the functionality, navigate to the ImageController file and add the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*/
public function create()
{
return view('image-upload');
}
/**
* Upload image and save image name.
*/
public function upload(Request $request) {
$validator = \Validator::make($request->all(), [
'image' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->fails()) {
return response()->json(['status' => 'error', 'message' => $validator->errors()]);
}
$data = [];
if ($request->hasfile('image')) {
$imageName = time().'.'.$request->image->extension();
$originalName = $request->image->getClientOriginalName();
if ($request->image->move(public_path('uploads'), $imageName)) {
$data = Image::create([
'image_name' => $imageName,
'image_original_name' => $originalName,
]);
}
}
if ($data) {
return response()->json(['status' => 'success', 'data' => $data, 'message' => 'Success! image uploaded']);
}
else {
return response()->json(['status' => 'failed', 'data' => $data, 'message' => 'Failed! image not uploaded']);
}
}
}
The above function of image upload contains validation rules for accepting file type as an image. Also, we defined the max file size to be uploaded.
After that, we added the functionality to upload the image. On successful upload, a successful response will be returned in the form of JSON.
Next, you need to add routes respective to the above functions.
How to Create a CRUD Application Using Ajax in Laravel 10
Add Routes For Image Upload
For adding the routes, you need to navigate to the web.php file. Now, add the below routes in order to run the application.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'create'])->name('image');
Route::post('image', [ImageController::class, 'upload'])->name('image.store');
At last, you need a view to handle form requests in which we will write some script as well.
Create a View For Image Upload Using Ajax in Laravel 10
Inside the views folder, simply create a blade file named image-upload.blade.php and then add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 10 AJAX Image Upload with Validation - 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">
<style>
.error {
color: #ff0000;
}
</style>
</head>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-8 col-md-8 col-sm-12 m-auto">
<form method="POST" id="upload-form" enctype="multipart/form-data">
@csrf
<div class="card shadow">
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z" />
</symbol>
<symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
</symbol>
</svg>
{{-- Display alert message --}}
<div id="response-container"></div>
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 10 Ajax Image Upload</h4>
</div>
<div class="card-body">
<div class="form-group">
<label> Image <span class="text-danger">*</span> </label>
<input type="file" name="image" id="image" class="form-control @error('image') is-invalid @enderror">
@error('image')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary"> 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')
}
});
$("#upload-form").validate({
rules: {
image: {
required: true,
}
},
messages: {
image: {
required: "Please upload the image",
}
},
submitHandler: function(form, event) {
event.preventDefault();
const formData = new FormData(form);
$.ajax({
url: "{{ route('image') }}",
type: 'POST',
data: formData,
processData: false,
cache: false,
contentType: false,
success: function(response) {
form.reset();
if (response && response.status === 'success') {
$("#response-container").append(`<div class="alert alert-success alert-dismissible d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Success:"> <use xlink:href="#check-circle-fill" /> </svg>
${response.message}<div><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div></div>`);
setTimeout(() => {
$(".alert").remove();
}, 5000);
}
else if(response.status === 'failed') {
$("#response-container").append(`<div class="alert alert-danger d-flex alert-dismissible align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill" /></svg>
<div> ${response.message} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div></div>`);
setTimeout(() => {
$(".alert").remove();
}, 5000);
}
else if(response.status === 'error') {
$("#response-container").append(`<div class="alert alert-danger d-flex alert-dismissible align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill" /></svg>
<div> ${response.message.image} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div></div>`);
setTimeout(() => {
$(".alert").remove();
}, 5000);
}
}
});
}
});
});
</script>
</body>
</html>
That’s it, now you are ready to run the application. Run the application by hitting the below command.
php artisan serve
Open the URL in the browser and check the result.
Leave a Reply