Laravel 8 Intervention Image Upload Tutorial

Laravel 8 intervention image upload and resize example. In this post, i will show you how to upload and resize image using intervention package in laravel 8 app.

As well as resize image by using intervention image and save to storage directory.

In this post example, i will create image intervention upload form in laravel 8. And resize image before upload to public storage directory using intervention image in laravel 8.

Laravel 8 Intervention Image Upload and Resize Tutorial

Simple steps to preview image before upload in laravel 8 app:

  • Step 1 – Install¬†Laravel 8¬†Application
  • Step 2 – Configuring Database Details
  • Step 3 – Install Intervention and Configure it
  • Step 4 – Create Image Model & Migration
  • Step 5 – Create Routes
  • Step 6 – Creating Controller
  • Step 7 – Create Image Upload Form
  • Step 8 – Start Development Server
  • Step 9 – Run This App On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Install Intervention and Configure it

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelImageUploadPreview

Then execute the following command to install image intervention package:

 composer  require intervention/image 

Then, register alieses and provider in app.php, which is locted inside config directory:

config/app.php

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

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

Step 4 – Create Image Model & Migration

Then create model and migration file by using the following command:

php artisan make:model Image -m

The above command will create two files into your laravel 8 image upload tutorial app, which is located inside the following locations:

  • LaravelImageIntervention/app/Models/Photo.php
  • LaravelImageIntervention/database/migrations/create_photos_table.php

So, find create_photos_table.php file inside LaravelImageIntervention/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->id();
            $table->string('original_img');
            $table->string('thumb_img');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 5 – Create Routes

In step 5, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageUploadController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('image-intervention', [ImageUploadController::class, 'index']);
Route::post('upload', [ImageUploadController::class, 'upload']);

Step 6 – Creating Controller

In step 6, create image upload controller by using the following command:

php artisan make:controller ImagUploadController

The above command will create ImagUploadController.php file, which is located inside LaravelImageIntervention/app/Http/Controllers/ directory.

The following laravel validation rules will validate image file before upload/save into database:

        $validatedData = $request->validate([
         'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
        ]);

So open ImagUploadController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Photo;
Use Image;
use Intervention\Image\Exception\NotReadableException;

class ImageUploadController extends Controller
{
     public function index()
    {
        return view('image-intervention');
    }

    public function upload(Request $request)
    {
        
        $validatedData = $request->validate([
         'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',

        ]);

        $file = $request->file('image')
             
        // for save original image
        $ogImage = Image::make($file);
        $originalPath = 'public/images/';
        $ogImage =  $ogImage->save($originalPath.time().$file->getClientOriginalName());
         
        // for store resized image
        $thumbnailPath = 'public/thumbnail/';
        $ogImage->resize(250,125);
        $thImage = $ogImage->save($thumbnailPath.time().$file->getClientOriginalName());


        $save = new Photo;

        $save->original_img = $ogImage;
        $save->thumb_img = $thImage;

        $save->save();

        return redirect('image')->with('status', 'Image Has been uploaded successfully with validation in laravel');

    }
}

Step 7 – Create Image Upload Form

In step 7, create new blade view file that named image-intervention.blade.php inside resources/views directory.

Note that, the following code display error message in laravel 8 image intervention forms. So do not forget to add the following code along laravel forms fields:

          @error('image')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror

So, you can add the following php and html form code into image-intervention.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Intervention Image Upload Tutorial</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-4">

  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 8 Intervention Image Upload Example</h2>
    </div>

    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" id="intervention-image-upload" action="{{ url('upload') }}" >
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="image" placeholder="Choose image" id="image">
                        @error('name')
                         <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                  
                <div class="col-md-12 mb-2">
                    <img id="preview-image" src="https://www.riobeauty.co.uk/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">Submit</button>
                </div>
            </div>     
        </form>
    </div>

  </div>
</div>  
</body>
</html>

Step 8 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel 8 intervention image upload application:

php artisan serve

Step 9 – Run This App On Browser

In step 9, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/image-intervention

Be First to Comment

Leave a Reply

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