Ajax image upload and preview with Laravel 11; Through this tutorial, i am going to show you how to display preview of image before upload image in Laravel 11 using jQuery ajax.
Ajax Image Upload and Preview with Laravel 11
Use the following simple steps to ajax image upload with preview in Laravel 11 apps:
- Step 1 – Installing Laravel 11 Application
- Step 2 – Configuring Database Details
- Step 3 – Creating Model & Migration
- Step 4 – Create Routes
- Step 5 – Creating Controller
- Step 6 – Create Blade View
- Step 7 – Start Development Server
- Step 8 – Run Laravel 11 Ajax Image Upload Preview App On Browser
Step 1 – Installing Laravel 11 Application
In step 1, open your terminal and navigate to your local web server directory using the following command:
//for windows user cd xampp/htdocs //for ubuntu user cd var/www/html
Then install laravel latest application using the following command:
composer create-project --prefer-dist laravel/laravel LaravelAjaxImageUploadPreview
Step 2 – Configuring Database Details
In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:
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
Step 3 – Creating Model & Migration
In step 3, open command prompt and navigate to your project by using the following command:
cd / LaravelAjaxImageUploadPreview
Then create model and migration file by using the following command:
php artisan make:model Image -m
The above command will create two files into your laravel ajax image upload with preview tutorial app, which is located inside the following locations:
- /app/Models/Image.php
- /database/migrations/create_images_table.php
So, find create_images_table.php file inside /database/migrations/ directory. Then open this file and add the following code into function up() on this file:
public function up() { Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('path'); $table->timestamps(); }); }
Now, open again your terminal and type the following command on cmd to create tables into your selected database:
php artisan migrate
Step 4 – Create Routes
In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AjaxImagePreviewController; /* |-------------------------------------------------------------------------- | 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::get('/', function () { return view('welcome'); }); Route::get('ajax-image-upload-preview', [AjaxImagePreviewController::class, 'index']); Route::post('upload-image-ajax', [AjaxImagePreviewController::class, 'ajaxUpload']);
Step 5 – Creating Controller
In step 5, create ajax image upload controller by using the following command:
php artisan make:controller AjaxImagePreviewController
The above command will create AjaxImagePreviewController.php file, which is located inside /app/Http/Controllers/ directory.
The following laravel validation rules will validate image file before upload/save into database:
$validatedData = $request->validate([ 'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048', ]);
So open AjaxImagePreviewController.php file and add the following code into it:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Image; class AjaxImagePreviewController extends Controller { public function index() { return view('ajax-image-preview'); } public function ajaxUpload(Request $request) { $validatedData = $request->validate([ 'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048', ]); $name = $request->file('image')->getClientOriginalName(); $path = $request->file('image')->store('public/images'); $save = new Image; $save->name = $name; $save->path = $path; $save->save(); return response()->json($path); } }
The following single line of code will upload image inside storage/app/public/images directory:
$path = $request->file('image')->store('public/images');
Step 6 – Create Blade View
In step 6, create new blade view file that named ajax-image-preview.php inside resources/views directory for image upload form.
Note that, the following ajax code will upload image on laravel controller:
$.ajax({ type:'POST', url: "{{ url('upload-image-ajax')}}", data: data, cache:false, contentType: false, processData: false, success: (data) => { $('#submit').html('Submit'); $("#submit"). attr("disabled", false); alert('Ajax form has been submitted successfully'); this.reset(); }, error: function(data){ console.log(data); } });
And the following jQuery code will display preview of image before upload:
$('#image').change(function(){ let reader = new FileReader(); reader.onload = (e) => { $('#preview-image').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); });
Don’t worry i have already added this code into ajax-image-preview.blade.php file.
So, you can add the following php and html form code into ajax-image-preview.blade.php:
<!DOCTYPE html> <html> <head> <title>Laravel 11 Ajax Image Upload With Preview Tutorial</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> <div class="container mt-4"> <div class="card"> <div class="card-header text-center font-weight-bold"> <h2>jQuery Ajax Image Upload with Preview in Laravel 11</h2> </div> <div class="card-body"> <form method="POST" enctype="multipart/form-data" id="ajax-image-upload-preview" action="javascript:void(0)" > <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="file" name="image" placeholder="Choose image" id="image"> </div> </div> <div class="col-md-12 mb-2"> <img id="preview-image" src="https://www.riobeauty.co.uk/images/product_image_not_found.gif" alt="preview image" style="max-height: 250px;"> </div> <div class="col-md-12"> <button type="submit" class="btn btn-primary" id="submit">Submit</button> </div> </div> </form> </div> </div> <script type="text/javascript"> $(document).ready(function (e) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#image').change(function(){ let reader = new FileReader(); reader.onload = (e) => { $('#preview-image').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); }); $('#ajax-image-upload-preview').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('upload-image-ajax')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { this.reset(); alert('Image has been uploaded using jQuery ajax successfully'); }, error: function(data){ console.log(data); } }); }); }); </script> </div> </body> </html>
Step 7 – Start Development Server
Finally, open your command prompt again and run the following command to start development server for your laravel ajax image upload with preview application:
php artisan serve
Step 8 – Run Laravel 11 Ajax Image Upload Preview App On Browser
In step 9, open your browser and fire the following url into your browser:
http://127.0.0.1:8000/ajax-image-upload-preview