Laravel 10 Intervention Image Upload Tutorial

Introduction

Intervention Image is a PHP image handling and manipulation library that provides an easier and expressive way to create, edit, and compose images. It is an open source library and it is available on GitHub.

In this tutorial, we will learn how to upload images in Laravel 10 using Intervention Image library. We will also learn how to resize and crop images before uploading them.

Prerequisites

Before starting this tutorial, you should have a basic understanding of the following:

Laravel 10

HTML

CSS

PHP

Step 1 – Install Intervention Image Library

First, we need to install the Intervention Image library. We can do this using Composer.

Run the following command in the terminal to install the library:

composer require intervention/image

Step 2 – Create a Model and Migration

Next, we need to create a model and migration for our images. We can do this using the Artisan command line tool.

Run the following command in the terminal to create a model and migration:

php artisan make:model Image -m

This will create a model and migration file for our images.

Step 3 – Configure the Database

Next, we need to configure the database. Open the migration file and add the following code:

public function up()
{
Schema::create(‘images’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(‘path’);
$table->timestamps();
});
}

This will create a table in the database with the name “images”.

Step 4 – Create a Form

Next, we need to create a form for uploading images. We can do this by creating a view file and adding the following code:

@csrf


This will create a form with a file input field and a submit button.

Step 5 – Create a Controller

Next, we need to create a controller for handling the image upload. We can do this using the Artisan command line tool.

Run the following command in the terminal to create a controller:

php artisan make:controller ImageController

This will create a controller file for our images.

Step 6 – Configure the Controller

Next, we need to configure the controller. Open the controller file and add the following code:

public function upload(Request $request)
{
// Validate the request
$request->validate([
‘image’ => ‘required|image|mimes:jpeg,png,jpg,gif,svg|max:2048’,
]);

// Get the image
$image = $request->file(‘image’);

// Generate a new filename.
$filename = time() . ‘.’ . $image->getClientOriginalExtension();

// Save the image
$path = $image->storeAs(‘images’, $filename);

// Create a new image record in the database
$image = Image::create([
‘name’ => $filename,
‘path’ => $path,
]);

// Return the response
return response()->json([
‘message’ => ‘Image uploaded successfully’,
‘image’ => $image
]);
}

This will create a controller action for handling the image upload.

Step 7 – Resize and Crop the Image

Next, we need to resize and crop the image before uploading it. We can do this using the Intervention Image library.

Add the following code to the controller action:

// Resize and crop the image
$img = Image::make($image->getRealPath());
$img->fit(300, 300, function ($constraint) {
$constraint->upsize();
});

// Save the image
$img->save($path);

This will resize and crop the image before uploading it.

Step 8 – Register the Route

Finally, we need to register the route for the controller action. Open the routes/web.php file and add the following code:

Route::post(‘image/upload’, ‘ImageController@upload’)->name(‘image.upload’);

This will register the route for the controller action.

Conclusion

In this tutorial, we have learned how to upload images in Laravel 10 using Intervention Image library. We have also learned how to resize and crop images before uploading them.

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 Intervention Images, you can easily upload, resize, crop, rotate, watermark, 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, 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, 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

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?