In this tutorial you will learn about the Laravel 7/6 Intervention Upload Image Using Ajax and its application with practical example.
Laravel 7/6 Intervention Upload Image Using Ajax
In this Laravel Intervention Image Upload Using Ajax example, we will learn how to upload and resize image using jquery ajax. In this tutorial I have used Intervention Image Package to upload and resize the image using jquery ajax and then save image into the database. This laravel image upload example is works with laravel version7, 6, 5.8 & 5.7 .
In this laravel image upload example, I’ll show you how to upload image into folder and then save it into database. In this tutorial before saving image into database we will resize the image and create it’s thumbnail image and then save it into thumbnail directory using the image intervention package.
Before uploading the image we will validate it using server side validation. In this example we will be uploading the image using jquery ajax without page refresh and reload. After successfully image upload into the database and folder we will display original image along with its thumbnail image (resize image).
- Install Laravel Fresh Setup
- Setup Database
- Install Image Intervention Package
- Generate migration file and model
- Make Route
- Create Controller & Methods
- Create Blade View
- Make Folder
- Run Development Server
- Conclusion
1). Install Laravel Fresh Setup
First of all we need to create a fresh laravel project, download and install Laravel 6 using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
2). Setup Database
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=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
3). Install Image Intervention Package
In this step, we will install Image intervention Package via the composer dependency manager. Use the following command to install image intervention Package.
1 |
composer require intervention/image |
After Installing Image intervention package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 |
config/app.php 'providers' => [ Intervention\Image\ImageServiceProvider::class ], 'aliases' => [ 'Image' => Intervention\Image\Facades\Image::class ] |
4). Generate Migration & Model
1 |
php artisan make:model Photo -m |
It command will create one model name Photo and also create one migration file for the Photo table. After successfully run the command go to database/migrations file and replace function, below here :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public function up() { Schema::create('photos', function (Blueprint $table) { $table->increments('id'); $table->string('photo_name'); $table->timestamps(); }); } |
Before we run PHP artisan migrate command go to app/providers/AppServiceProvider.php and put the below code :
1 2 3 4 5 6 7 8 9 |
... use Illuminate\Support\Facades\Schema; .... function boot() { Schema::defaultStringLength(191); } ... |
Next, migrate the table using the below command :
1 |
php artisan migrate |
5). Make Route
now, create two routes in the web.php file.
web.php
1 2 |
Route::get('image', 'ImageController@index'); Route::post('save-image', 'ImageController@save'); |
6). Create Controller
Next, we have to create a controller for image uploading and resizing. Create a controller named ImageController using command given below –
1 |
php artisan make:controller ImageController |
Once the above command executed, it will create a controller file ImageController.php in app/Http/Controllers directory. Open the ImageController.php file and put the following code in it.
app/Http/Controllers/ImageController.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 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response,File; Use Image; Use App\Photo; use Intervention\Image\Exception\NotReadableException; class ImageController extends Controller { public function index() { return view('image'); } public function save(Request $request) { request()->validate([ 'photo_name' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($files = $request->file('photo_name')) { // for save original image $ImageUpload = Image::make($files); $originalPath = 'public/images/'; $ImageUpload->save($originalPath.time().$files->getClientOriginalName()); // for save thumnail image $thumbnailPath = 'public/thumbnail/'; $ImageUpload->resize(250,125); $ImageUpload = $ImageUpload->save($thumbnailPath.time().$files->getClientOriginalName()); $photo = new Photo(); $photo->photo_name = time().$files->getClientOriginalName(); $photo->save(); } $image = Photo::latest()->first(['photo_name']); return Response()->json($image); } } |
7). Create Blade view
In this step, we need to create a blade view file. Go to app/resources/views and create one file name image.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 |
<!DOCTYPE html> <html> <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 Using Intervention Package Example</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <style> .avatar-pic { width: 300px; } </style> </head> <body> <div class="container"> <h3 style="margin-top: 12px;" class="text-center alert alert-success">Laravel Ajax Image Upload Using Intervention Package Example</h3> <br> <div class="row justify-content-center"> <div class="col-md-8"> <form id="imageUploadForm" action="javascript:void(0)" enctype="multipart/form-data"> <div class="file-field"> <div class="row"> <div class=" col-md-8 mb-4"> <img id="original" src="" class=" z-depth-1-half avatar-pic" alt=""> <div class="d-flex justify-content-center mt-3"> <div class="btn btn-mdb-color btn-rounded float-left"> <input type="file" name="photo_name" id="photo_name" required=""> <br> <button type="submit" class="btn btn-secondary d-flex justify-content-center mt-3">submit</button> </div> </div> </div> <div class=" col-md-4 mb-4"> <img id="thumbImg" src="" class=" z-depth-1-half thumb-pic" alt=""> </div> </div> </form> </div> </div> </div> </body> </html> |
Now we will implement a laravel ajax image upload script, put the below script after the closing of the body tag.
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 |
<script> $(document).ready(function (e) { $('#imageUploadForm').on('submit',(function(e) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('save-image')}}", data:formData, cache:false, contentType: false, processData: false, success:function(data){ $('#original').attr('src', 'public/images/'+ data.photo_name); $('#thumbImg').attr('src', 'public/thumbnail/'+ data.photo_name); }, error: function(data){ console.log(data); } }); })); }); </script> |
8). Make Folder
1 2 3 |
Go to public folder => first create folder name images => second create folder name thumbnail |
9). Run Development Server
1 2 3 |
php artisan serve If you want to run the project diffrent port so use this below command php artisan serve --port=8080 |
Now we are ready to run our example so run bellow command to quick run.
1 |
http://127.0.0.1:8000/image |