How to Install and Use Image Intervention in Laravel

Intervention Image has optional support for Laravel and comes with a Service Provider and Facades for easy integration. In addition, laravel includes the vendor/autoload.php file, so you don’t have to require or autoload manually. Also, I have used the intervention/image package to resize the image and then save the image into the database.

Step 1: Install Laravel Project

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

Step 2: Set up a MySQL database

Configure this database in the .env file.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelinterventionimage
DB_USERNAME=root
DB_PASSWORD=

I have set up local database credentials.

Next, migrate two tables provided by Laravel Move to your terminal and hit the following command.

php artisan migrate 

It will establish three tables in your database.

  1. users
  2. password_resets
  3. failed_jobs

Step 3: Construct a model and migration file for our image_model table

Type the following command in your terminal.

php artisan make:model ImageModel -m 

It will create two files.

  1. ImageModel.php model.
  2. create__image_models_table migration file.

We need to create a Schema for the passports table. So navigate to Laravel  >>  database  >>  migrations  >>  create__image_models_table.

// Create__image_models_table

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('image_models', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

Step 4: Build a view file to add the image to the database

Create a file in the resources  >>  views  >>   createimage.blade.php and put the following code in it.

// createimage.blade.php

<html lang="en">
<head>
  <title>Laravel  Image Intervention</title>
  <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  Image Intervention </h3>
    <form method="post" action="{{url('create')}}" 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>     
  </form>
  </div>
</body>
</html>

Laravel 5 Intervention image upload and resize tutorial

Step 5: Create one controller and route

php artisan make:controller ImageController --resource 

It will create one controller file called ImageController.php.

We register routes in routes  >>  web.php file. So let us do it.

// web.php

Route::get('create','ImageController@create');
Route::post('create','ImageController@store');

The next step would be to go to the ImageController.php file and add some code to the create() function.

// ImageController.php

  /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createimage');
    }

After that, we require the beginning Laravel Development server. So in the terminal, follow the following command.

php artisan serve

Go to the browser and hit this URL: http://localhost:8000/create

Step 6: Install Intervention Image Package

Move to your terminal and type the following command.

composer require intervention/image 

Find the providers in config >> app.php file and register the ImageServiceProvider.

'providers' => [
        // ...
        'Intervention\Image\ImageServiceProvider',
    ]

Locate the aliases in config >> app.php file and register the aliases.

'aliases' => [
        // ...
        'Image' => 'Intervention\Image\Facades\Image',
    ]

The Intervention Image uses PHP’s GD library extension to process all images by default. However, to switch to Imagick, you can pull a configuration file into your application by running one of the following artisan commands.

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

In recent Laravel applications, the configuration file is copied to config/image.php in older Laravel 4 applications; you will find the file at app/config/packages/intervention/image/config.php.

With this copy, you can alter the image driver settings for your application locally.

Step 7: Save Data into the Database.

We require coding the store function in sequence to store the data in the database. We can programmatically create the two folders, but let us manually create two folders in the public directory called images and thumbnails.

//ImageController.php

use App\ImageModel;
use Image;

public function store(Request $request)
    {
       
        $originalImage= $request->file('filename');
        $thumbnailImage = Image::make($originalImage);
        $thumbnailPath = public_path().'/thumbnail/';
        $originalPath = public_path().'/images/';
        $thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
        $thumbnailImage->resize(150,150);
        $thumbnailImage->save($thumbnailPath.time().$originalImage->getClientOriginalName()); 

        $imagemodel= new ImageModel();
        $imagemodel->filename=time().$originalImage->getClientOriginalName();
        $imagemodel->save();

        return back()->with('success', 'Your images has been successfully Upload');

    }

Step 8: Define Validation for Image

Add validation in the Store function.

//ImageController.php

public function store(Request $request)
    {
        $this->validate($request, [
            'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
         ]);
    }

If there is any validation, Fail it through error.

Laravel 5 Intervention image upload and resize example

Next, we pass an image to the blade file to display images.

// ImageController.php

public function create()
    {
        $image = ImageModel::latest()->first();
        return view('createimage', compact('image'));
    }

The final Code of Controller looks like below.

//ImageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\ImageModel;
use Image;

class ImageController extends Controller
{

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $image = ImageModel::latest()->first();
        return view('createimage', compact('image'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
         ]);
        $originalImage= $request->file('filename');
        $thumbnailImage = Image::make($originalImage);
        $thumbnailPath = public_path().'/thumbnail/';
        $originalPath = public_path().'/images/';
        $thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
        $thumbnailImage->resize(150,150);
        $thumbnailImage->save($thumbnailPath.time().$originalImage->getClientOriginalName()); 

        $imagemodel= new ImageModel();
        $imagemodel->filename=time().$originalImage->getClientOriginalName();
        $imagemodel->save();

        return back()->with('success', 'Your images has been successfully Upload');

    }

}

Step 9: Modify the View File

We can display an image in the view file, so add some code in the view file for the display image.

//createimage.blade.php

       @if($image)
   	    <div class="row">
	     <div class="col-md-8">
		      <strong>Original Image:</strong>
		      <br/>
		      <img src="/images/{{$image->filename}}" />
	    </div>
	    <div class="col-md-4">
		    <strong>Thumbnail Image:</strong>
		    <br/>
		    <img src="/thumbnail/{{$image->filename}}"  />
	   	 </div>
   		</div>
		@endif


The final Code of View file looks like the one below.

//createimage.blade.php

<html lang="en">
<head>
  <title>Laravel  Image Intervention</title>
  <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">
  @if(session('success'))
        <div class="alert alert-success">
          {{ session('success') }}
        </div> 
        @endif
        @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
    <h3 class="jumbotron">Laravel  Image Intervention </h3>
  <form method="post" action="{{url('create')}}" 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>
        @if($image)
   	    <div class="row">
	     <div class="col-md-8">
		      <strong>Original Image:</strong>
		      <br/>
		      <img src="/images/{{$image->filename}}" />
	    </div>
	    <div class="col-md-4">
		    <strong>Thumbnail Image:</strong>
		    <br/>
		    <img src="/thumbnail/{{$image->filename}}"  />
	   	 </div>
   		</div>
		@endif       
  </form>
  </div>
</body>
</html>

Laravel Intervention image upload and resize tutorialThat’s it.

7 thoughts on “How to Install and Use Image Intervention in Laravel”

  1. Hello,
    Thanks for this tutorial, it’s well explained. But I am on Windows platform with Laragon and I have issues on saving file.
    I got the message :

    Intervention \ Image \ Exception \ NotWritableException
    Can’t write image data to path (D:\htdocs\shareholders\public/avatars/images/1534280739logo.png)

    I create another code which uses Illuminate\Support\Facades\Storage. There I can save the file but when I got the path and set it on ‘src’ image tag, the file is not rendered although the path is corect and the file exists.

    Reply
    • You can first add folders in your public folder then only you can use these codes, if you will not make folders in advance it will give these WRITE ERRORS.

      Folder names are images and thumbnail

      Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.