Laravel 10, Ajax allows for asynchronous image uploading, which means that the user can continue interacting with the webpage while the image is being uploaded in the background. This provides a smoother and more responsive user experience compared to traditional form submissions.
Step 1: Install Laravel App
composer create-project laravel/laravel example-AjaxImagUpload
Step 2: Create Migration and Model
php artisan make:migration create_images_table
database/migrations/2022_02_10_1488880_create_images_table.php
<?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(): void
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('images');
}
};
Run migration command,
php artisan migrate
Now create Image model by using following command:
php artisan make:model Image
app/Models/Image.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}
Step 3: Create Controller
php artisan make:controller ImageController
app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('imageUpload');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\JsonResponse
*/
public function store(Request $request): JsonResponse
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$imageName = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $imageName);
Image::create(['name' => $imageName]);
return response()->json('Image uploaded successfully');
}
}
Store Images in Storage Folder
$image->storeAs('images', $imageName);
// storage/app/images/file.png
Store Images in Public Folder
$image->move(public_path('images'), $imageName);
// public/images/file.png
Store Images in S3
$image->storeAs('images', $imageName, 's3');
Step 4: Create and Add Routes
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(ImageController::class)->group(function(){
Route::get('image-upload', 'index');
Route::post('image-upload', 'store')->name('image.store');
});
Step 5: Create Blade File
resources/views/imageUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Ajax Image Upload Example - webthestuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Laravel 10 Ajax Image Upload Example - webthestuff.com</h2>
</div>
<div class="panel-body">
<img id="preview-image" width="300px">
<form action="{{ route('image.store') }}" method="POST" id="image-upload" enctype="multipart/form-data">
@csrf
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3">
<label class="form-label" for="inputImage">Image:</label>
<input
type="file"
name="image"
id="inputImage"
class="form-control">
<span class="text-danger" id="image-input-error"></span>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
/*------------------------------------------
--------------------------------------------
File Input Change Event
--------------------------------------------
--------------------------------------------*/
$('#inputImage').change(function(){
let reader = new FileReader();
reader.onload = (e) => {
$('#preview-image').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
/*------------------------------------------
--------------------------------------------
Form Submit Event
--------------------------------------------
--------------------------------------------*/
$('#image-upload').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#image-input-error').text('');
$.ajax({
type:'POST',
url: "{{ route('image.store') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
this.reset();
alert('Image has been uploaded successfully');
},
error: function(response){
$('#image-upload').find(".print-error-msg").find("ul").html('');
$('#image-upload').find(".print-error-msg").css('display','block');
$.each( response.responseJSON.errors, function( key, value ) {
$('#image-upload').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
</script>
</html>
Run Laravel App:
php artisan serve
Now, Go to web browser, type the given URL and see the output:
http://localhost:8000/image-upload