Laravel Intervention Image Save to Storage

Laravel Intervention Image Save to Storage

Laravel Image Intervention Package – Today we would love to share with how to use image 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.

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 folder using the image intervention package.

When we upload the image we will validate image using server side validation and html validation. We will upload the image using jquery ajax without page refresh and reload.

After successfully image upload into the database and folder. When we have successfully form submit after few second we got ajax response. we will use the ajax response data and display original image and thumbnail image (resize image).

Laravel intervention image upload and save to storage

Use the following steps and image upload in laravel using intervention package with save to storage:

  1. Install Laravel App
  2. Setup Database
  3. Install Image Intervention Package
  4. Generate migration file and model
  5. Make Route For Save and Display Image And Thumbnail
  6. Create Controller For Store Image & Thumbnail
  7. Create Blade View
  8. Make Folder
  9. Start Development Server

Install Laravel App

First of we need to download laravel fresh setup. Use the below command and download fresh new laravel setup :

composer create-project --prefer-dist laravel/laravel LaravelIntervention

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

Install Image Intervention Package

Now We need to install laravel image intervention package for resizing the image size. use the below command and install it.

 composer  require intervention/image 

After successully install laravel image intervention package. Register image intervention package to providers and alies go to app/config/app.php register here .

config/app.php

'providers' => [
Intervention\Image\ImageServiceProvider::class
],

'aliases' => [
'Image' => Intervention\Image\Facades\Image::class
]

Generate Migration & Model

Now we will create 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 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

Make Route For Save and Display Image And Thumbnail

We will create two routes in 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');

Create Controller For Store Image & Thumbnail

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);


}
}

Create Blade view

In this step we need to create 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 5.7 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 laravel ajax image upload script, put the below script after closing of 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> 

Make Folder

Now create two folder where we store our images. First folder name images that store without resize image and second folder name thumnail that store resize image :

Go to public folder 
=> first create folder name images
=> second create folder name thumbnail

Start Development Server

In this 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
or 
http://localhost/blog/public/image

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this laravel intervention image upload example, we have successfully install
rvention package and resize and store the image in database and folder in laravel based application and we have successully image upload without page refresh and reload using ajax.

Recommended Laravel Posts

  1. Laravel Upload Image Using Dropzone js Tutorial
  2. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  3. Laravel CKEditor with Image Upload
  4. Ajax Image Upload in Laravel Example From Scratch
  5. Laravel Upload Image to Database with Validation

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Laravel Intervention Image Save to Storage

  1. Great tutorial, thanks a lot!!!

Leave a Reply

Your email address will not be published. Required fields are marked *