Laravel 10 Ajax Image Upload with Preview Image - WebJourney
If you are looking how to upload image in Laravel 10 and Ajax just read the article step by step. In this tutorial we will learn how to upload and how to show image preview with validation error message as well as success message using Laravel, Ajax, JavaScript and jQuery. We do all actions without refresh the page. So lets create a image_uploads table and store the image. For uploading image we will need the bellow steps. So if you see example upload image by laravel 10 and ajax follow the follwing steps.
1. Install laravel 10
2. Create Database
3. Create Model Migration
4. Create Controller
5. Create Required Routes
6. Create Image Upload Page
7. Create Js File
8. Test Application
Step 1. Install laravel 10
Create a fresh laravel project using the composer command. We will make a project laravel-ajax-image-upload with the bellow command.
composer create-project laravel/laravel laravel-ajax-image-upload
Step 2. Create Database
Create a database and connect to tha project. we will create a database ajax_image_upload and save database info like database name, database username and password in .env
DB_DATABASE=your database name
DB_USERNAME=your database username
DB_PASSWORD=your database password
If you haven't password then keep it empty and set default database username root
DB_DATABASE=ajax_image_upload
DB_USERNAME=root
DB_PASSWORD=
Step 3. Create Model Migration
Now we will create a model class ImageUpload and a migration file using the bellow artisan command.
php artisan make:model ImageUpload -m
-m will create the migation file
2023_03_19_173427_create_image_uploads_table.php
Now open the migration file and add image column as shown bellow.
<?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('image_uploads', function (Blueprint $table) {
$table->id();
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('image_uploads');
}
};
Create Table
Run the following artisan migrate command to create the table.
php artisan migrate
Now open the ImageUpload.php class and update as shown bellow.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ImageUpload extends Model
{
use HasFactory;
protected $fillable = ['image'];
}
Step 4 Create Controller
Now we need to create ImageUploadController and write require code for image upload inside the controller. Let's run the following command to create controller.
php artisan make:controller ImageUploadController
Step 5. Create Required Routes
Open web.php file and make required routes like bellow.
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageUploadController;
Route::get('/',[ImageUploadController::class,'image_upload'])->name('image.upload');
Route::post('/store',[ImageUploadController::class,'image_store'])->name('image.store');
Update ImageUploadController.php
App\Http\Controllers\ImageUploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ImageUpload;
class ImageUploadController extends Controller
{
public function image_upload()
{
return view('image-upload-form');
}
public function image_store(Request $request)
{
if($request->ajax()){
$request->validate([
'image'=>'required|mimes:jpg,jpeg,png,gif,svg'
]);
if($image = $request->file('image')){
$imageName = time().'-'.uniqid().'.'.$image->getClientOriginalExtension();
$image->move('images', $imageName);
}
ImageUpload::create([
'image'=>$imageName
]);
return response()->json([
'status'=>'success'
]);
}
}
}
Step 6. Create Image Upload Page
In this step we will create image upload form inside resources/view folder. We will also show upload image preview, validation error message and success message after the image has successfully uploaded.
resources/view/image-upload-form.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Ajax Image Upload By WebJourney.</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-3">
<div class="row">
<div class="offset-md-3 col-md-6">
<form id="image_upload_form" enctype="multipart/form-data">
<h4>Laravel Ajax Image Upload By WebJourney</h4>
<div class="error_success_msg_container my-3"></div>
<img src="" width="200" height="100" class="image_preview">
<div class="form-group mt-3">
<input class="form-control" type="file" name="image" id="image">
</div>
<button class="btn btn-primary mt-2" type="submit">Submit</button>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
@include('image-upload-js')
</body>
</html>
Step 7. Create Js File
Now create a js file inside resources/view folder.
resources/view/image-upload-js.blade.php
<script>
$(document).ready(function(){
//todo:image preview
$(document).on('change','#image', function() {
$('.error_success_msg_container').html('');
if (this.files && this.files[0]) {
let img = document.querySelector('.image_preview');
img.onload = () =>{
URL.revokeObjectURL(img.src);
}
img.src = URL.createObjectURL(this.files[0]);
document.querySelector(".image_preview").files = this.files;
}
});
//todo:update image
$(document).on('submit','#image_upload_form',function(e){
e.preventDefault();
let form_data = new FormData(this);
$.ajax({
url:"{{ route('image.store') }}",
method:'post',
data:form_data,
cache:false,
contentType: false,
processData: false,
success:function(res){
$('.error_success_msg_container').html('');
$('.image_preview').hide();
if(res.status=='success'){
$('.error_success_msg_container').html('<p class="text-success">Image Successfully Uploaded</p>');
}
},
error:function(err){
let error = err.responseJSON;
$('.error_success_msg_container').html('');
$.each(error.errors, function (index, value) {
$('.error_success_msg_container').append('<p class="text-danger">'+value+'<p>');
});
}
});
});
})
</script>
Step 8. Test Application
Open the terminal and start the laravel server. To start server run the following command.
php artisan serve
Now open any browser and paste the link in the url and hit enter.
http://127.0.0.1:8000/
Image Preview
Image Upload Success Message
Image Upload Validation Error Messages
All the steps has done. If you think this article is usefull please subscribe our youtbe channel Youtube Channel: WebJourney. Feel free to ask any query about this post in the comment section. Thanks to read the full post.
If you like what you are reading, please think about buying us a coffee as a token of appreciation.
We appreciate your support and are committed to providing you useful and informative content.
We are thankful for your ongoing support.
You May Read Bellow Articles:
Laravel 9 live search data in a table using ajax.
How to send SMS in laravel 9 using Twilio SMS API-Webjourney
Laravel 9 pdf invoice generate and download with barryvdh dompdf
How to create multi language website by laravel 9
Laravel image crud with radio, checkbox, email, date, text, number, color, select box