Laravel 11 Generate Thumbnail Image Example

Websolutionstuff | Aug-26-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to generate thumbnail images in laravel 11. Here, we'll use the spatie/image composer package to generate thumbnails in laravel 11. This PHP package makes it super easy to apply common manipulations to images like resizing, cropping, and adding effects.

In this example, we will install the Spatie/Image Composer package. The Spatie/Image package offers methods to resize images, such as the read() and resize() methods. We'll create a simple form with a file input field where you can select an image. Once selected, you'll see a preview of both the original image and the resized thumbnail.

Laravel 11 Generate Thumbnail Image Example

Laravel 11 Generate Thumbnail Image Example

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-example

 

Step 2: Install spatie/image Package

Next, we'll install the spatie/image composer package using the following command.

composer require spatie/image

 

Step 3: Define Routes

Then, we'll define the routes in the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

 

Step 4: Create Controller File

Now, we'll create a controller file using the following command.

php artisan make:controller ImageController

app/Http/Controllers/ImageController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Spatie\Image\Image;
  
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('image-upload');
    }
        
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $this->validate($request, [
            'image' => ['required'],
        ]);
        
        $imageName = time().'.'.$request->image->extension();  

        $destinationPath = public_path('/images/');
        $request->image->move($destinationPath, $imageName);

        $destinationPathThumbnail = public_path('images/thumbnail/');
        Image::load($destinationPath. $imageName)
                ->resize(200, 150)
                ->save($destinationPathThumbnail. $imageName);
        
        return back()->with('success', 'You have successfully upload image.')
                     ->with('imageName', $imageName); 
    }
}

Note: create a images folder in the public directory. and in the images folder create a thumbnail folder.

 

Step 5: Create a Blade File

Next, we'll create a blade file and create a form to upload images.

resources/views/image-upload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Generate Thumbnail Image Example - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
        
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Generate Thumbnail Image Example - Websolutionstuff</h3>
        <div class="card-body">

            @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
  
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>

                <div class="row">
                    <div class="col-md-4">
                        <strong>Original Image:</strong>
                        <br/>
                        <img src="/images/{{ Session::get('imageName') }}" width="300px" />
                    </div>
                    <div class="col-md-4">
                        <strong>Thumbnail Image:</strong>
                        <br/>
                        <img src="/images/thumbnail/{{ Session::get('imageName') }}" />
                    </div>
                </div>
            @endsession
            
            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Image:</label>
                    <input 
                        type="file" 
                        name="image" 
                        id="inputImage"
                        class="form-control @error('image') is-invalid @enderror">
        
                    @error('image')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
                </div>
             
            </form>
        </div>
    </div>
</div>
</body>
      
</html>

 

Step 6: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
7+ Laravel tips: DB Models and Eloquent (2023)
7+ Laravel tips: DB Models and...

Welcome to our latest guide on mastering Laravel's DB Models and Eloquent, updated for 2023. If you're a web dev...

Read More

Nov-08-2023

Reseller Hosting Myths to Know and Unfollow
Reseller Hosting Myths to Know...

If you work in the web hosting sector, you're probably acquainted with the term reseller hosting. Resellers make up...

Read More

Apr-07-2022

How To Create Zip File Using Ziparchive in Laravel
How To Create Zip File Using Z...

In this article, we will see how to create a zip file using zipArchive in laravel. Sometimes we have requirements to hav...

Read More

Sep-16-2020

500 Internal Server Error In Laravel 9 AJAX
500 Internal Server Error In L...

In this article, we will see 500 internal server errors in laravel 9 ajax. Also, we can see how to solve or fixed l...

Read More

Apr-17-2022