New Laravel 6 Image upload using the Intervention Package – This tutorial explains to you how you can upload the image using ajax and intervention package. The intervention package and resize the image size using the laravel image intervention package and we will upload the image using ajax and jquery with validation. This example tutorial also work with laravel 7.x version.
In this laravel image upload example. We will image upload to database and folder, before upload image in database and folder we will resize the image and save it to the folder using the image intervention package.
After successfully image upload into the database and folder. When we have successfully form submit after few seconds we got ajax response. we will use the ajax response data and display the original image and thumbnail image (resize the image).
Laravel 6 Ajax Image Upload With Intervention Package
Just follow the below steps and upload the image using the laravel intervention package:
- 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, we need to download the laravel fresh setup. Use the below command and download fresh new laravel setup :
composer create-project --prefer-dist laravel/laravel blog
2). Setup Database
After successfully install laravel Application, Go to your project .env file and set up database credential and move next step :
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
Now We need to install the laravel image intervention package for resizing the image size. use the below command and install it.
composer require intervention/image
After successfully install a laravel image intervention package. Register image intervention package to providers and aliases go to app/config/app.php register here.
config/app.php
'providers' => [
Intervention\Image\ImageServiceProvider::class
],
'aliases' => [
'Image' => Intervention\Image\Facades\Image::class
]
4). Generate Migration & Model
Now we will create a table name Photo and it’s migration file. use the below command :
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 :
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 :
...
use Illuminate\Support\Facades\Schema;
....
function boot()
{
Schema::defaultStringLength(191);
}
...
Next, migrate the table using the below command :
php artisan migrate
Recommended Post
Laravel Upload image Using Dropzone Example5). Make Route
We will create two routes in the web.php file. Go to app/routes/web.php file and create two below routes here :
Route::get('image', 'ImageController@index');
Route::post('save-image', 'ImageController@save');
6). Create Controller
We need to create a controller name ImageController. Use the below command and create Controller :
php artisan make:controller ImageController
After successfully create controller go to app/controllers/ImageController.php and put the below code :
<?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 :
<!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 - Tutsmake.com</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 5.7 Ajax Image Upload Using Intervention Package Example - <a href="https://www.tutsmake.com" target="_blank">TutsMake</a></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.
<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
Now create two folders where we store our images. First folder name images that store without resize image and second folder name thumbnail that store resizes the image :
Go to public folder
=> first create folder name images
=> second create folder name thumbnail
9). Run Development Server
In this last step, we will use the PHP artisan serve command. It will start your server locally
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.
http://127.0.0.1:8000/image
10). Conclusion
In this laravel intervention image upload example, we have successfully installed
intervention package and resize and store the image in database and folder in laravel based application and we have successfully image upload without page refresh and reload using ajax.
If you have any questions or thoughts to share, use the comment form below to reach us.
Useful article!