In this tutorial you will learn about the Laravel 6 Intervention Image Upload Using Ajax and its application with practical example.
Laravel 6 Intervention Image Upload 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 version 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).
Basic Usage Of Intervention Image Package
Create Instance :-
1 |
$img = Image::make('public/foo.jpg') |
Resize Image to Fixed Size :-
1 |
$img->resize(300, 200); |
Resize Image Width:-
1 2 |
// resize only the width of the image $img->resize(300, null); |
Resize Image Height:-
1 2 |
// resize only the height of the image $img->resize(null, 200); |
Resize Width with Aspect Ratio:-
1 2 3 4 |
// resize the image to a width of 300 and constrain aspect ratio (auto height) $img->resize(300, null, function ($constraint) { $constraint->aspectRatio(); }); |
Resize Height with Aspect Ratio:-
1 2 3 4 |
// resize the image to a height of 200 and constrain aspect ratio (auto width) $img->resize(null, 200, function ($constraint) { $constraint->aspectRatio(); }); |
Prevent Possible Upsizing:-
1 2 3 4 |
$img->resize(null, 400, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); |
Install Laravel 6
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 laravelIntervention |
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=larabIntervention DB_USERNAME=root DB_PASSWORD= |
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 |
Register Package
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 |
'providers' => [ Intervention\Image\ImageServiceProvider::class ], 'aliases' => [ 'Image' => Intervention\Image\Facades\Image::class ] |
Generate Migration
Now, we have to define table schema for photos table. Open terminal and let’s run the following command to generate a migration file to create photos table in our database.
1 |
php artisan make:migration create_photos_table |
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 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePhotosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('photos', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('photo_name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('photos'); } } |
Run Migration
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 along with migrations, password_resets and users table.
Create Model
Next, we need to create a model called Photo using below command.
1 |
php artisan make:model Photo |
Once, the above command is executed it will create a model file Photo.php in app directory.
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 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response,File; use App\Photo; use Image; use Intervention\Image\Exception\NotReadableException; class ImageController extends Controller { public function AjaxIndex(){ return view('AjaxInterventionImageUpload.index'); } public function AjaxStore(Request $request){ request()->validate([ 'filename' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($files = $request->file('filename')) { // for save original image $ImageUpload = Image::make($files); $originalPath = public_path('/profile_images/'); $ImageUpload->save($originalPath.time().$files->getClientOriginalName()); // for save thumnail image $thumbnailPath = public_path('/profile_images/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); } } |
Here In the controller, we have following methods –
AjaxIndex() :- It displays Image Upload Form along with Uploaded Image and its thumbnail
AjaxStore() :- To Upload and Resize Image with Intervention Package using Ajax.
Note:- Before uploading any file make sure you have created following two directory in the public folder called profile_images and /profile_images/thumbnail.
If you want to resize the image proportionally and maintain image aspect ratio then you can use add aspectRatio constraint like this –
Example :-
1 2 3 4 |
$img = Image::make($thumbnailpath)->resize(250, 125, function($constraint) { $constraint->aspectRatio(); }); $img->save($thumbnailpath); |
Example 1:-
1 |
$img = Image::make($thumbnailpath)->resize(100, 100)->save($thumbnailpath); |
and image will not cut off. We are passing width as 400 and height as 150. You can change these values as per your requirement.
If you are looking for hard crop then replace below lines
Create Blade / View Files
In this step, we will create view/blade file to generate and display Image Upload Form. Lets create a blade file “index.blade.php” in “resources/views/AjaxInterventionImageUpload/” directory and put the following code in it respectively.
resources/views/AjaxInterventionImageUpload/index.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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
<html lang="en"> <head> <title>Laravel Intervention Image Upload Using Ajax - W3Adda</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3 class="jumbotron">Laravel Intervention Image Upload Using Ajax - W3Adda</h3> <form method="post" id="FrmImgUpload" action="javascript:void(0)" enctype="multipart/form-data"> @csrf <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <input type="file" name="filename" class="form-control"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success" style="margin-top:10px">Upload Image</button> </div> </div> <div class="row"> <div class="col-md-8"> <strong>Original Image:</strong> <br/> <img id="ImgOri" src="" /> </div> <div class="col-md-4"> <strong>Thumbnail Image:</strong> <br/> <img id="ImgThumb" src="" /> </div> </div> </form> </div> </body> </html> <script> $(document).ready(function (e) { $('#FrmImgUpload').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('intervention-ajax-image-upload')}}", data:formData, cache:false, contentType: false, processData: false, success:function(data){ $('#ImgOri').attr('src', "/profile_images/"+ data.photo_name); $('#ImgThumb').attr('src', "/profile_images/thumbnail/"+ data.photo_name); }, error: function(data){ console.log(data); } }); })); }); </script> |
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 |
Route::get('intervention-ajax-image-upload', 'ImageController@AjaxIndex'); Route::post('intervention-ajax-image-upload', 'ImageController@AjaxStore'); |
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 –
http://localhost:8000/intervention-ajax-image-upload
Output:-
After Image Upload Screen Output:-