In this tutorial you will learn about the Laravel 9 Ajax Image Upload with Preview Tutorial and its application with practical example.
In this Laravel 9 Ajax Image Upload with Preview Tutorial I’ll show you how to upload image using ajax with preview in laravel 9. In this tutorial you will learn how to upload image and display preview using ajax before upload in laravel 9. I will also show you how to upload image using jQuery and ajax and display preview without reloading of page. In this laravel 9 ajax image upload with preview example we will upload image using ajax and display preview of the image and then save it into directory. Before uploading the image we will display preview of the image and then after successfully image upload into the database and folder we will display success message on the screen.
Laravel 9 Ajax Image Upload with Preview Tutorial
In this step by step ajax image upload with preview in laravel 9 tutorial you will learn to upload image with preview using jQuery and ajax in laravel 9. In this example I’ll share the process to upload image with preview using ajax in laravel 9. Please following steps given below:
- Install Laravel 9
- Database Configuration
- Build Model & Migration
- Create Routes
- Generate Controller By Artisan Command
- Create Ajax Image Upload Form
- Create Images Directory inside Storage/app/public
- Run Development Server
Install Laravel 9
First of all we need to create a fresh laravel project, download and install Laravel 9 using the below command
1 |
composer create-project --prefer-dist laravel/laravel SimpleImageUpload |
Configure Database In .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=SimpleImageUpload DB_USERNAME=root DB_PASSWORD= |
Create Model & Migration
Now, we have to define table schema for photos table. Open terminal and let’s run the following command to generate a migration along with model file to create photos table in our database.
1 |
php artisan make:model Photo -m |
Once this command is executed you will find a migration file created under “database/migrations”. lets open migration file and put following code in it –
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('photos', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('path'); $table->timestamps(); }); } |
Now, run following command to migrate database schema.
1 |
php artisan migrate |
After, the migration executed successfully the photos table will be created in database.
Create Routes
After this, we need to add following routes in “routes/web.php” file along with a resource route. Lets open “routes/web.php” file and add following route.
routes/web.php
1 2 3 4 |
use App\Http\Controllers\AjaxUploadController; Route::get('image-preview', [AjaxUploadController::class, 'index']); Route::post('upload', [AjaxUploadController::class, 'store']); |
Create Controller By Artisan Command
Now, lets create a controller for simple image uploading. Create a controller named AjaxUploadController using command given below –
1 |
php artisan make:controller AjaxUploadController |
Once the above command executed, it will create a controller file AjaxUploadController.php in app/Http/Controllers/ directory. Open the AjaxUploadController.php file and put the following code in it.
app/Http/Controllers/AjaxUploadController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Photo; class AjaxUploadController extends Controller { public function index() { return view('image-upload-preview-form'); } public function store(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 Photo; $save->name = $name; $save->path = $path; $save->save(); return response()->json($path); } } |
Note:- Before uploading any file make sure you have created following directory in the storage/app/public folder called images
.
Create Ajax Image Upload Form
In this step, we will create view/blade file to generate and display Image Upload Form. Lets create a blade file “image-upload-preview-form.blade.php” in “resources/views/” directory and put the following code in it respectively.
resources/views/image-upload-preview-form.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<!DOCTYPE html> <html> <head> <title>Laravel 9 Ajax Image Upload With Preview</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"> <h2 class="text-center">Image Upload with Preview using jQuery Ajax in Laravel 9</h2> <form method="POST" enctype="multipart/form-data" id="image-upload" 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-before-upload" src="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> <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-before-upload').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); }); $('#image-upload').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('upload')}}", 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> |
Create Images Directory inside Storage/app/public
Before uploading any file make sure you have created following directory in the storage/app/public folder called images
.
Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/image-preview |