Using Ajax, you can upload image in Laravel 9. The image upload functionality will remain same as you did with normal upload. We will prevent the form refreshing on image upload. Only the form request will be sent out using Ajax. In this process, I will handle the file validation and file processing using jQuery. Previously, we created a CRUD Application using Ajax. So, we are going to create something like shown below.
There will be form validation. For the form validation, I will be using jQuery Validator.
After choosing the image, hit the upload button.
You will get a success alert as shown below If image is uploaded.
So, these are the functionalities which are be covered in this post.
Prerequisites
IFor creating a new project in Laravel 9, you must have the below configurations.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Create a Laravel App For Ajax Image Upload
This step is not mandatory if you already have a project setup. If you don’t have the project setup, please create a new one using the below command.
composer create-project --prefer-dist laravel/laravel ajax-upload
Next, connect your application with a database.
How to Upload Multiple Files in Laravel 9 with Validation
Create and Configure Database
Navigate to the .env file and configure the database as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
Replace the database name, username and the password respectively.
Next, create a Model, Migration and a Controller.
Upload Multiple Images in Laravel 9 with Validation
Create a Model, Migration and a Controller
You can create these three files together using the below command.
php artisan make:model Image -mc
Once, these files are created, let’s proceed with the migration.
Add Migration For Images Table
Navigate to the image 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 adding the schema, let’s migrate it to the database.
php artisan migrate
Next, you will have to add the fillable property in the Image model.
How to Upload Image in Laravel 9 with Validation
Add Mass Assignment in Image Model
Open the Image model 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, add the functionality for file handling in the controller.
Form Validation in Laravel 9 with Custom Error Messages
Add Image Upload Functionality in Laravel 9
Navigate to the ImageController.php file and add the below snippet.
<?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([
'image' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$data = [];
if ($request->hasfile('image')) {
$name = time().rand(1,100).'.'.$request->image->extension();
if ($request->image->move(public_path('uploads'), $name)) {
$data = Image::create(["imageName" => $name]);
}
}
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']);
}
}
}
Next, create a view for Ajax image upload and form handling.
Create a View For Ajax Image Upload in Laravel 9
Inside the view folder, create a new blade file named upload.blade.php. After creating the file, add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 9 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-6 col-md-6 col-sm-12 m-auto">
<div id="result"></div>
<div class="card">
<form id="uploadForm" method="POST" enctype="multipart/form-data">
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 9 Image Upload Using Ajax </h4>
</div>
<div class="card-body">
<label for="file"> Image <span class="text-danger">*</span> </label>
<input type="file" name="image" class="form-control @error('image') is-invalid @enderror">
@error('image')
<div class="invalid-feedback">{{ $message }} </div>
@enderror
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</form>
</div>
</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: {
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') {
$("#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>
In the bottom, I have added the script for form validation, and Ajax image upload. Through the submit handler, we handled the form submit action.
Last, but not least, you will need to add routes.
Add Routes For Ajax Image Upload
For adding routes, navigate to the web.php file. Then 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');
That’s it for the functionality. Now, the application is ready to upload the image.
Conclusion
We covered the Ajax upload functionality and form handling. We have added a basic validation for image while uploading. For the validation, we have used jQuery validator. So, I hope this will help you to bring it in use in your real applications.
Leave a Reply