Laravel 10 Intervention Image Upload Tutorial

Laravel 10 Intervention Image Upload Tutorial

Laravel Intervention Image is a popular PHP library that provides image handling and manipulation capabilities for the Laravel web framework. It is built on top of the GD (GIF Draw) library and provides a more convenient and expressive way of working with images in Laravel applications.

With Laravel 10 Intervention Image, you can easily resize, crop, rotate, watermark, upload and apply various image filters to images. It simplifies common image-related tasks and allows developers to perform these tasks using a clean and intuitive syntax.

In this tutorial, you will learn how to upload, resize, crop, rotate, watermark, cache, encode, decode, and apply various image filters to images using intervention/image in laravel 10 web applications.

Intervention Image Upload Laravel 10

Steps to upload, resize, crop, rotate, watermark, cache, encode, decode, and apply various image filters to images using intervention/image in laravel 10 web applications.

  • Step 1 – Setup New Laravel 10 Application
  • Step 2 – Setup Database with Laravel App
  • Step 3 – Install Intervention Image Package
  • Step 4 – Define Routes
  • Step 5 – Create Controller By Artisan Command
  • Step 6 – Create Blade View
  • Step 7 – Run Development Server

Step 1 – Setup New Laravel 10 Application

First of all, start your terminal to download or install Laravel 10 new setup. Run the following commands in it to install the new Laravel 10 app on your system:

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

Step 2 – Database with Laravel App

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

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

Step 3 – Install Intervention Image Package

In this step, open again your command prompt. And run the following command on it to install intervention/image package in your Laravel projects:

composer require intervention/image

Next, Open the config/app.php file and update the following code in the file to configure intervention/image package.

<?php

return [

	......

	$providers => [

		......,

		'Intervention\Image\ImageServiceProvider'

	],

	$aliases => [

		......,

		'Image' => 'Intervention\Image\Facades\Image'

	]

]

Then, open again command prompt and run the following command to create tables in database:

php artisan migrate

Step 4 – Add Routes

In this step, Visit your routes directory and open web.php file in any text editor. And add the following routes into web.php route file:

<?php

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

/*
|--------------------------------------------------------------------------
| 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('/file-resize', [ImageInterventionController::class, 'index']);

Route::post('/resize-file', [ImageInterventionController::class, 'ImageManipulate'])->name('ImageManipulate');

Step 5 – Create Controller By Artisan Command

In this step, execute the following command on terminal/command prompt/command line to create controller file for your laravel applications; is as follow:

php artisan make:controller ImageInterventionController

After that, go to app/http/controllers and open ImageInterventionController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;

class ImageInterventionController extends Controller
{
    
    public function index()
    {
    	return view('welcome');
    }

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

        $image = $request->file('file');
        $input['file'] = time().'.'.$image->getClientOriginalExtension();
        
        $destinationPath = public_path('/thumbnail');

        $imgFile = Image::make($image->getRealPath());

        $imgFile->resize(150, 150, function ($constraint) {
		    $constraint->aspectRatio();
		})->save($destinationPath.'/'.$input['file']);

        $destinationPath = public_path('/uploads');
        $image->move($destinationPath, $input['file']);

        return back()
        	->with('success','Image has successfully uploaded.')
        	->with('fileName',$input['file']);
    }

}

Step 6 – Create Blade View

Now, create an image upload form in the blade view file to submit and store images in directories and databases.

So, Go to resources/views and create welcome.blade.php and update the following code into it:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<title>Laravel Image Resize Example</title>
</head>
<body>
<div class="container mt-5" style="max-width: 550px">
<h2 class="mb-5">Laravel Image Upload Intervention Example - Tutsmake.com</h2>     
<form action="{{route('ImageManipulate')}}" method="post" enctype="multipart/form-data">
@csrf
@if ($message = Session::get('success'))
<div class="alert alert-success">
<strong>{{ $message }}</strong>
</div>
<div class="col-md-12 mb-3">
<strong>Grayscale Image:</strong><br/>
<img src="/uploads/{{ Session::get('fileName') }}" width="550px" />
</div>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="custom-file">
<input type="file" name="file" class="custom-file-input" id="chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<button type="submit" name="submit" class="btn btn-outline-danger btn-block mt-4">
Upload
</button>
</form>
</div>
</body>
</html>

Step 7 – Run Development Server

The last step, open the command prompt and run the following command to start development server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/file-resize

Conclusion

Congratulations! You have learned how to install and configure the image intervention library to upload, resize, crop, rotate, watermark, and apply various image filters to images using intervention/image in laravel 10 web applications.

Recommended Laravel Posts

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.

Leave a Reply

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