In this article, we will see how to image upload using ajax in laravel 9. Here, we will learn about image upload in laravel 7, laravel 8, and laravel 9 using jquery ajax. So, you can upload an image without page refresh in laravel 8 and laravel 9.
So, let's see laravel 9 image upload using ajax, upload image in laravel 8 using ajax, and image upload with ajax in laravel 8 and laravel 9.
For this example, we will create a migration and model. So, we will store the image in the database using jquery ajax call in laravel 9.
In this step, we will install the laravel 9 application using the following command.
composer create-project laravel/laravel laravel-9-ajax-image-upload
Now, we will create a model and migration using the following command.
php artisan make:migration create_images_table
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.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
};
After that, we will migrate the image table to the database using the following command.
php artisan migrate
Now, we will create an Image model using the below 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'
];
}
In this step, we will create ImageController using the following command.
php artisan make:controller ImageController
app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('image_upload');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image_name = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image_name);
Image::create(['name' => $image_name]);
return response()->json('Image uploaded successfully');
}
}
In this step, we will create routes in the web.php file.
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('upload-image', 'index');
Route::post('upload-image', 'store')->name('image.store');
});
Now, we will create an image_upload.blade.php file. So, add the below code to that file.
resources/views/image_upload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How To Image Upload Using Ajax In Laravel 9 - Websolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>How To Image Upload Using Ajax In Laravel 9 - Websolutionstuff</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="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">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#inputImage').change(function(){
let reader = new FileReader();
reader.onload = (e) => {
$('#preview-image').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
$('#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) => {
if (response) {
this.reset();
alert('Image has been uploaded successfully');
}
},
error: function(response){
$('#image-input-error').text(response.responseJSON.message);
}
});
});
</script>
</html>
Now, we will laravel 9 image upload using jquery ajax using the following command.
php artisan serve
You might also like:
- Read Also: How To Create Calendar Event In Laravel 9 Using AJAX
- Read Also: How To Show Loading Spinner In Ajax jQuery
- Read Also: Laravel 9 CRUD With Image Upload Example
- Read Also: Laravel 9 AJAX CRUD Example