AppDividend
Latest Code Tutorials

Laravel Image Intervention Tutorial with Example

2,633

Get real time updates directly on you device, subscribe now.

Laravel Image Intervention Tutorial with Example is the topic, we will discuss today in this tutorial, we use laravel’s current version 5.6.15. Also, I have used intervention/image package to resize the image and then save the image into the database. We have generally the use cases like upload an avatar or upload a product image of specific size on an e-commerce website. So intervention/image package is used to upload and resize the images.

Laravel Image Intervention Tutorial with Example

First, we install Laravel Project.

Step 1: Install Laravel Project

We install laravel project by typing following command.

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

Step 2: Setup a MySQL database

Now, 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 5.6 Move to your terminal and hit the following command.

php artisan migrate

It will establish two tables in your database.

  1. users
  2. password_resets  

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 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 view file to add the Image in 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 route in routes  >>  web.php file. So let us do it.

//web.php

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

Next step would be to go to ImageController.php file and add into create() function some code.

// ImageController.php

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

After that, we require 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

Related Posts
1 of 37

Move to your terminal type 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',
    ]

Step 7: Save Data into Database.

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

//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 Store function.

//ImageController.php

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

If any validation Fail it through error.

Laravel 5 Intervention image upload and resize example

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

//ImageController.php

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

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 View File

We can display image in view file so add some code in 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


Final Code of View file looks like 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 tutorial

Finally, Our Laravel Image Intervention Tutorial with Example is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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