PHPackages                             moonlight-poland/laravel-context-aware-thumbnails - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. moonlight-poland/laravel-context-aware-thumbnails

ActiveLibrary[Image &amp; Media](/categories/media)

moonlight-poland/laravel-context-aware-thumbnails
=================================================

Context-Aware on-demand thumbnail generation for Laravel with intelligent path organization, Smart Crop, AVIF/WebP support, Laravel Native Signed URLs, and variants system. Automatically organize thumbnails by user/post/album. Zero config, blazing fast! Laravel 12+ ready.

3.1.1(4mo ago)014MITPHPPHP ^8.1|^8.2|^8.3CI passing

Since Jan 3Pushed 4mo agoCompare

[ Source](https://github.com/Moonlight4000/laravel-thumbnails)[ Packagist](https://packagist.org/packages/moonlight-poland/laravel-context-aware-thumbnails)[ RSS](/packages/moonlight-poland-laravel-context-aware-thumbnails/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (22)Used By (0)

🖼️ Laravel Context-Aware Thumbnails™
====================================

[](#️-laravel-context-aware-thumbnails)

### Intelligent On-Demand Image Thumbnails with Smart Crop &amp; Modern Formats

[](#intelligent-on-demand-image-thumbnails-with-smart-crop--modern-formats)

> **Copyright © 2024-2026 Moonlight Poland. All rights reserved.**
> **Contact:**
> **License:** [Commercial License](LICENSE.md) - Free for personal use, paid for commercial use
> **Repository:**

[![Latest Version on Packagist](https://camo.githubusercontent.com/0aee1d32894b2d24ef9076e67799509332ebb9feb982891a59287e62b98421b9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6f6f6e6c696768742d706f6c616e642f6c61726176656c2d636f6e746578742d61776172652d7468756d626e61696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/moonlight-poland/laravel-context-aware-thumbnails)[![Total Downloads](https://camo.githubusercontent.com/5021b23f070729230a519bbe3dfc3574f30435dc299afd7e5d519941f619aa43/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6f6f6e6c696768742d706f6c616e642f6c61726176656c2d636f6e746578742d61776172652d7468756d626e61696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/moonlight-poland/laravel-context-aware-thumbnails)[![License: Commercial](https://camo.githubusercontent.com/0d0aab9fbb6c301620a97e87ebdfa88d339321ccf48a519a6c5f5636a4740949/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d436f6d6d65726369616c2d626c75652e737667)](LICENSE.md)

Generate image thumbnails on-the-fly in Laravel with **Context-Aware Thumbnails™** - the only package that organizes thumbnails exactly where your content lives!

**No pre-generation needed. No Redis required. Smart organization included.™**

### 🌟 What Makes Us Unique?

[](#-what-makes-us-unique)

1. **🎯 Context-Aware Organization™** - Thumbnails organized by user/post/album (no other package does this!)
2. **⚛️ React/Vue/JavaScript Support** - The ONLY Laravel thumbnail package with `sync-js` command for frontend frameworks
3. **🔐 Signed URLs (Facebook-style)** - Time-limited, cryptographically signed URLs to prevent hotlinking
4. **🤖 Smart Crop with AI Energy Detection** - Automatically focuses on important image areas
5. **🚀 AVIF/WebP Support** - Modern formats for 50%+ smaller file sizes
6. **🔒 Commercial Licensing** - Professional support &amp; tamper detection included

---

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [Why Choose This Over Other Packages?](#-why-choose-this-over-other-packages)
- [What Makes Context-Aware Thumbnails™ Special?](#-what-makes-context-aware-thumbnails-special)
- [License Notice](#%EF%B8%8F-license-notice)
- [Features](#-features)
- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Configuration](#-configuration)
- [Usage](#-usage)
    - [Blade Directive](#blade-directive)
    - [Helper Function](#helper-function)
    - [Eloquent Trait](#eloquent-trait)
    - [React / Vue / JavaScript Usage](#react--vue--javascript-usage)
    - [Signed URLs (Facebook-style Protection)](#-signed-urls-facebook-style-protection)
- [Context-Aware Thumbnails™](#-context-aware-thumbnails)
- [Advanced Features](#-advanced-features)
- [Artisan Commands](#-artisan-commands)
- [Testing](#-testing)
- [Contributing](#-contributing)
- [License](#-license)
- [Credits](#-credits)

---

🏆 Why Choose This Over Other Packages?
--------------------------------------

[](#-why-choose-this-over-other-packages)

### 📊 Complete Feature Comparison

[](#-complete-feature-comparison)

Feature**Laravel Smart Thumbnails™
(moonlight-poland)****askancy/
laravel-smart-thumbnails****lee-to/
laravel-thumbnails****spatie/
laravel-medialibrary****🎯 UNIQUE FEATURES****Context-Aware Organization™**✅ **ONLY US!**❌❌❌Custom path templates✅ `{user_id}/{post_id}`❌❌⚠️ LimitedPer-user/post isolation✅ Built-in❌ Manual❌ Manual⚠️ Via DBCommercial licensing✅ $500-$15k❌ MIT (free)❌ MIT✅ Spatie**🖼️ IMAGE PROCESSING**AVIF format support✅ **v2.0+**✅❌✅WebP format support✅ **v2.0+**✅❌✅Smart Crop (AI energy)✅ **v2.0+**✅❌✅Crop/Fit/Resize methods✅ All 3✅ SmartCrop✅ All 3✅ YesMultiple drivers✅ GD/Imagick/Intervention✅ GD/Imagick⚠️ Intervention only✅ YesQuality control✅ Per size✅ Per variant✅ Global✅ Yes**🛡️ ERROR HANDLING**Silent/Strict modes✅ **v2.0+**✅❌⚠️ LimitedBulletproof fallbacks✅✅⚠️ Basic✅Never breaks app✅✅⚠️ Can throw✅**⚡ GENERATION**On-demand (lazy)✅ Automatic✅ Automatic✅ Manual✅ ManualMiddleware fallback✅ Auto 404→generate❌❌❌Zero config✅ Works out-of-box⚠️ Requires setup⚠️ Setup needed❌ Complex**📁 ORGANIZATION**Subdirectory strategies✅ Context-aware✅ 5 strategies❌ Flat⚠️ Via DBHash-based distribution⚠️ Manual✅ Automatic❌❌Date-based folders⚠️ Manual✅ Automatic❌❌Handles millions of files✅ Yes✅ Yes⚠️ Slow✅ Yes**🎨 VARIANTS &amp; PRESETS**Multiple sizes per preset✅✅ Variants✅✅Responsive images✅✅✅✅Named presets✅ `'small'`, `'large'`✅✅✅**🔧 DEVELOPER EXPERIENCE**Blade directive✅ `@thumbnail()`❌❌❌Helper function✅ `thumbnail()`❌✅❌Eloquent trait✅ `HasThumbnails`❌✅✅**React/Vue/JS**✅ **ONLY US!**❌❌❌Auto-sync JS helper✅ `sync-js`❌❌❌Artisan commands✅ generate, clear, sync-js✅ purge, optimize❌✅ Many**📊 MONITORING**Statistics &amp; analytics✅ **v2.0+**✅ Full❌✅Performance metrics✅ **v2.0+**✅❌⚠️Disk usage tracking✅ **v2.0+**✅❌✅**🔒 SECURITY**File validation✅ **v2.0+**✅⚠️ Basic✅Size limits✅ **v2.0+**✅❌✅Extension whitelist✅ **v2.0+**✅❌✅**Signed URLs (Facebook-style)**✅ **v2.0.16+**❌❌⚠️ Via S3Time-limited links✅ **v2.0.16+**❌❌❌Hotlinking prevention✅ **v2.0.16+**❌❌⚠️ Via S3Tamper detection✅ Commercial only❌❌❌**💾 STORAGE**Filesystem cache✅✅✅✅Redis/Memcached tags❌✅❌⚠️Multi-disk support✅✅✅✅S3/Cloud storage✅✅✅✅Database storage❌❌❌✅**📦 INSTALLATION**Installs🆕 New17~50050,000+Stars⭐ New1~505,000+Maturity🆕 v2.0.1🆕 v2.0⚠️ v1.x✅ v11.x### 🎯 Which Package Should You Choose?

[](#-which-package-should-you-choose)

#### Choose **Laravel Context-Aware Thumbnails™ (moonlight-poland)** if you need:

[](#choose-laravel-context-aware-thumbnails-moonlight-poland-if-you-need)

- ✅ **Context-Aware organization** (unique feature!)
- ✅ Thumbnails organized by user/post/album automatically
- ✅ **React/Vue/JavaScript support** (ONLY package with sync-js!)
- ✅ **Signed URLs (Facebook-style)** - Time-limited, cryptographically signed protection
- ✅ **Auto-strategy**: Context-Aware for models, Hash for paths
- ✅ **Smart Crop with energy detection** (v2.0)
- ✅ **AVIF/WebP modern formats** (v2.0)
- ✅ **Variants system** for multiple sizes (v2.0)
- ✅ **Daily usage statistics** sent to Moonlight (v2.0)
- ✅ Blade directives and helpers for easy use
- ✅ Automatic middleware fallback
- ✅ Commercial support with licensing
- ✅ Simple filesystem-based solution

---

🔥 What Makes Context-Aware Thumbnails™ Special?
-----------------------------------------------

[](#-what-makes-context-aware-thumbnails-special)

**Other packages dump all thumbnails in one folder. We organize them exactly where your content lives:**

```
❌ OTHER PACKAGES:
storage/thumbnails/
  ├── user1_avatar_thumb_small.jpg
  ├── post42_image_thumb_small.jpg
  ├── gallery_photo_thumb_small.jpg
  └── ... 10,000+ files in one folder!

✅ CONTEXT-AWARE THUMBNAILS™:
storage/
  ├── user-posts/1/12/thumbnails/image_thumb_small.jpg
  ├── galleries/5/3/thumbnails/photo_thumb_medium.jpg
  ├── avatars/8/thumbnails/avatar_thumb_small.jpg
  └── fanpages/42/photos/thumbnails/banner_thumb_large.jpg

```

**Benefits:**

- ✅ **Delete post** → thumbnails automatically deleted with folder
- ✅ **Per-user backups** → backup specific user folders
- ✅ **CDN routing** → route different contexts to different CDNs
- ✅ **Filesystem performance** → fewer files per directory = faster I/O
- ✅ **Security** → isolate user content with directory permissions
- ✅ **Organization** → find thumbnails instantly, no database queries

---

⚠️ License Notice
-----------------

[](#️-license-notice)

**This is a COMMERCIAL package with a dual-licensing model:**

- 🆓 **FREE** for personal/non-commercial use
- 💼 **PAID** for commercial use ($500-$15,000/year)

See [LICENSE.md](LICENSE.md) for details.

**Contact:**
**GitHub:**

---

✨ Features
----------

[](#-features)

- 🔥 **Context-Aware Thumbnails™** - Organize thumbnails by user/post/album/any structure (UNIQUE!)
- 🚀 **On-Demand Generation** - Thumbnails generated only when requested (lazy loading)
- 🔐 **Signed URLs (Facebook-style)** - Time-limited, cryptographically signed URLs to prevent hotlinking
- 💾 **Filesystem Cache** - Fast subsequent loads, no Redis/Memcached needed
- 🔌 **Zero Configuration** - Sensible defaults, works out of the box
- 🎨 **Multiple Drivers** - GD (default), Imagick, or Intervention Image
- 📐 **3 Resize Methods** - Resize (proportional), Crop (exact size), Fit (with padding)
- 🔧 **Fully Configurable** - Custom sizes, quality, drivers, paths, and more
- 🎯 **Blade Directive** - `@thumbnail('path/image.jpg', 'small', 'post', ['user_id' => 1])`
- ⚛️ **React/Vue/JavaScript Helper** - Full feature parity with PHP (sync-js command)
- 📦 **Facade &amp; Helpers** - Multiple ways to use
- 🗑️ **Auto Cleanup** - Delete folder = thumbnails gone
- 🛠️ **Artisan Commands** - Generate or clear thumbnails via CLI
- ✅ **Laravel 10 &amp; 11** - Full support for modern Laravel

---

📦 Installation
--------------

[](#-installation)

```
composer require moonlight-poland/laravel-smart-thumbnails
```

### Optional Dependencies (Recommended)

[](#optional-dependencies-recommended)

For best performance and advanced features, install these optional packages:

```
# Intervention Image - Required for Smart Crop and better performance
composer require intervention/image

# Imagick Extension - Required for AVIF format support
# (Install via your system's package manager, e.g., apt install php-imagick)
```

**What you get with optional dependencies:**

- ✅ **Smart Crop** - AI-powered energy detection (requires Intervention Image)
- ✅ **AVIF format** - Modern image format with 50% smaller files (requires ext-imagick)
- ✅ **Better performance** - Intervention Image is faster than GD for large images
- ⚠️ **Without them** - Package falls back to GD (works, but limited features)

### License Activation

[](#license-activation)

**For Personal (Free) use:**

```
php artisan thumbnails:license --type=personal
```

**For Commercial use:**

```
# Enter your license key (from purchase email)
php artisan thumbnails:license YOUR-LICENSE-KEY
```

**Contact for licensing:**

### Optional: Publish Config

[](#optional-publish-config)

```
php artisan vendor:publish --tag=thumbnails-config
```

### Make Sure Storage is Linked

[](#make-sure-storage-is-linked)

```
php artisan storage:link
```

### For React/Vue Apps: Generate JS Helper

[](#for-reactvue-apps-generate-js-helper)

**REQUIRED if using React, Vue, or any JavaScript framework:**

```
php artisan thumbnails:sync-js
```

This generates `resources/js/utils/thumbnails.js` with your config contexts.

**When to run:**

- ✅ After installation
- ✅ After changing `config/thumbnails.php`
- ✅ After adding new contexts

See [React/Vue Usage](#-react--vue--javascript-usage) section below for details.

---

🚀 Quick Start
-------------

[](#-quick-start)

### Basic Usage (Blade)

[](#basic-usage-blade)

```
{{-- Original image --}}

{{-- Thumbnail (auto-generated on first request!) --}}

```

**That's it!** 🎉

- **First request**: Generates thumbnail (~50-200ms)
- **Next requests**: Cached file served by Nginx (~1-5ms)

---

🔥 Context-Aware Thumbnails™ (UNIQUE FEATURE!)
---------------------------------------------

[](#-context-aware-thumbnails-unique-feature)

**The only Laravel package that organizes thumbnails exactly where your content lives!**

### Why Context Matters

[](#why-context-matters)

Traditional packages dump all thumbnails into one folder. This causes:

- ❌ Messy filesystem (thousands of files in one directory)
- ❌ Difficult cleanup (delete post, but thumbnails remain)
- ❌ No per-user isolation
- ❌ CDN routing nightmare
- ❌ Slow backups (can't backup specific content types)

**Context-Aware Thumbnails™ solves this:**

```
{{-- USER POST CONTEXT --}}

{{-- Result: /storage/user-posts/1/12/thumbnails/image_thumb_small.jpg --}}

{{-- GALLERY CONTEXT --}}

{{-- Result: /storage/galleries/5/3/thumbnails/photo_thumb_medium.jpg --}}

{{-- AVATAR CONTEXT --}}

{{-- Result: /storage/avatars/8/thumbnails/avatar_thumb_small.jpg --}}

{{-- NO CONTEXT (default) --}}

{{-- Result: /storage/thumbnails/cat_thumb_small.jpg --}}
```

### Configuration

[](#configuration)

Define custom contexts in `config/thumbnails.php`:

```
'contexts' => [
    // User posts - separate per user and post
    'post' => 'user-posts/{user_id}/{post_id}',

    // Gallery - separate per user and album
    'gallery' => 'galleries/{user_id}/{album_id}',

    // Avatars - per user only
    'avatar' => 'avatars/{user_id}',

    // Fanpage content
    'fanpage' => 'fanpages/{fanpage_id}/{type}',

    // Your custom contexts
    'product' => 'products/{category_id}/{product_id}',
    'team' => 'companies/{company_id}/team',
],
```

### PHP Usage

[](#php-usage)

```
// In controllers
$url = thumbnail('image.jpg', 'small', true, 'post', [
    'user_id' => auth()->id(),
    'post_id' => $post->id
]);

// Helper functions
$url = thumbnail_url('photo.jpg', 'medium', 'gallery', [
    'user_id' => $user->id,
    'album_id' => $album->id
]);

// Facade
use Thumbnail;
$url = Thumbnail::generate('avatar.jpg', 'small', true, 'avatar', [
    'user_id' => $user->id
]);
```

### Model Integration

[](#model-integration)

```
use Moonlight\Thumbnails\Traits\HasThumbnails;

class UserPost extends Model
{
    use HasThumbnails;

    // Define default context for this model
    protected $thumbnailContext = 'post';

    // Provide context data automatically
    public function getThumbnailContextData(): array
    {
        return [
            'user_id' => $this->user_id,
            'post_id' => $this->id,
        ];
    }
}

// In Blade - context applied automatically!

{{-- Auto-uses 'post' context with user_id and post_id --}}
```

### Benefits

[](#benefits)

✅ **Perfect organization** - thumbnails live with their content
✅ **Easy cleanup** - delete post folder, thumbnails gone
✅ **Per-user isolation** - great for multi-tenant apps
✅ **CDN-friendly** - route `/user-posts/1/*` to User 1's CDN
✅ **Faster backups** - backup specific content types
✅ **Better performance** - fewer files per directory

---

🎨 React / Vue / JavaScript Usage
--------------------------------

[](#-react--vue--javascript-usage)

> **🌟 UNIQUE FEATURE:** We are the **ONLY Laravel thumbnail package** that provides seamless React/Vue/JavaScript integration with automatic context synchronization! Other packages only work with Blade.

**IMPORTANT:** For React/Vue apps, you need to generate a JavaScript helper that mirrors your PHP config.

### Step 1: Generate JS Helper

[](#step-1-generate-js-helper)

```
php artisan thumbnails:sync-js
```

This creates `resources/js/utils/thumbnails.js` with your contexts from `config/thumbnails.php`.

**Run this command whenever you:**

- Change `config/thumbnails.php`
- Add new contexts
- Change filename patterns

### Step 2: Import in React/Vue

[](#step-2-import-in-reactvue)

**✅ YES, the import is REQUIRED!** Without it, your React/Vue components won't have thumbnail URLs.

```
// React Component
import { getThumbnailUrl } from '@/utils/thumbnails';

function PostMedia({ post }) {
    const mediaFiles = post.media_files || [];

    return (

            {mediaFiles.map((media, index) => (

            ))}

    );
}
```

### Available Functions

[](#available-functions)

```
import {
    getThumbnailUrl,              // Basic usage
    getThumbnailUrlWithContext,   // With Context-Aware
    buildContextPath,             // Build context path only
    THUMBNAIL_CONTEXTS,           // Available contexts
    THUMBNAIL_SIZES               // Available sizes
} from '@/utils/thumbnails';

// Basic usage (path already includes context)
const url = getThumbnailUrl('user-posts/1/12/img.jpg', 'small');
// → /storage/user-posts/1/12/thumbnails/img_thumb_small.jpg

// With crop method + WebP format
const url = getThumbnailUrl('user-posts/1/12/img.jpg', 'small', {
    method: 'crop',      // crop, fit, or resize
    format: 'webp',      // webp, avif, jpg, png
    quality: 85,         // 1-100
    smart_crop: true     // AI energy detection (v2.0+)
});
// → /storage/user-posts/1/12/thumbnails/img_thumb_small_crop.webp?quality=85&smart_crop=1

// Context-Aware (filename + context + data)
const url = getThumbnailUrlWithContext(
    'img.jpg',              // Just filename
    'small',                // Size
    'post',                 // Context
    { user_id: 1, post_id: 12 },  // Context data
    { method: 'crop', format: 'webp' }  // Options (optional)
);
// → /storage/user-posts/1/12/thumbnails/img_thumb_small_crop.webp

// Build context path only
const path = buildContextPath('post', { user_id: 1, post_id: 12 });
// → user-posts/1/12
```

### ✅ Full Feature Parity with PHP

[](#-full-feature-parity-with-php)

JavaScript helper supports **ALL** PHP features:

- ✅ **Context-Aware paths** - Organized by user/post/album
- ✅ **Resize methods** - `crop`, `fit`, `resize`
- ✅ **Modern formats** - `webp`, `avif`, `jpg`, `png`
- ✅ **Quality control** - 1-100
- ✅ **Smart Crop** - AI energy detection (v2.0+)
- ✅ **On-demand generation** - Middleware handles 404

**Example with all options:**

```
// React Component with Smart Crop + WebP
function PostMedia({ post }) {
    return (

            {post.media_files.map((media, idx) => (

            ))}

    );
}
```

### PHP Backend Setup for React

[](#php-backend-setup-for-react)

In your **PHP accessor** (e.g., `UserPost.php`):

```
// Return ONLY path, React will build thumbnail URL
public function getMediaFilesAttribute(): array
{
    $mediaFiles = [];

    foreach ($this->attachments as $attachment) {
        if ($attachment['type'] === 'image') {
            $mediaFiles[] = [
                'type' => $attachment['type'],
                'path' => $attachment['path'],  // e.g., 'user-posts/1/12/img.jpg'
                'url' => asset('storage/' . $attachment['path']),
                'alt' => $attachment['original_name'],
            ];
        }
    }

    return $mediaFiles;
}
```

**React will:**

1. Call `getThumbnailUrl(media.path, 'small')`
2. Build URL: `/storage/user-posts/1/12/thumbnails/img_thumb_small.jpg`
3. Browser requests thumbnail
4. **404** on first request → middleware generates thumbnail
5. **200** on next requests → cached file served by Nginx

### Workflow

[](#workflow)

```
┌─────────────────────────────────────────────────────────┐
│ 1. Change config/thumbnails.php                        │
│    (add new context, change pattern, etc.)             │
└─────────────────────────────────────────────────────────┘
                        ↓
┌─────────────────────────────────────────────────────────┐
│ 2. Run: php artisan thumbnails:sync-js                 │
│    Generates: resources/js/utils/thumbnails.js         │
└─────────────────────────────────────────────────────────┘
                        ↓
┌─────────────────────────────────────────────────────────┐
│ 3. Commit thumbnails.js to git                         │
│    (single source of truth in PHP, synced to JS)       │
└─────────────────────────────────────────────────────────┘
                        ↓
┌─────────────────────────────────────────────────────────┐
│ 4. React uses getThumbnailUrl() automatically          │
│    (always in sync with PHP config)                    │
└─────────────────────────────────────────────────────────┘

```

### Vue Example

[](#vue-example)

```

import { getThumbnailUrl } from '@/utils/thumbnails';

const props = defineProps({
    post: Object
});

```

---

📦 Benefits
----------

[](#-benefits)

1. **✅ Automatic Cleanup** - Delete post folder = all thumbnails gone
2. **✅ Per-User Isolation** - Easy permissions &amp; backups per user
3. **✅ CDN Routing** - Route different contexts to different CDNs
4. **✅ Performance** - Fewer files per directory = faster filesystem
5. **✅ Organization** - Find any thumbnail instantly
6. **✅ Scalability** - No "one folder with million files" problem

---

📐 Resize Methods
----------------

[](#-resize-methods)

Choose how thumbnails should be generated:

### 1. **Resize** (Default - Proportional)

[](#1-resize-default---proportional)

```
// config/thumbnails.php
'method' => 'resize',
```

- ✅ Preserves aspect ratio
- ✅ No cropping
- ⚠️ Final size may differ slightly from target

**Use for:** Product images, photos where full content must be visible

### 2. **Crop** (Exact Size - Center Crop)

[](#2-crop-exact-size---center-crop)

```
// config/thumbnails.php
'method' => 'crop',
```

- ✅ Exact dimensions guaranteed
- ✅ Fills entire thumbnail
- ⚠️ May cut edges (center-focused)

**Use for:** Avatars, thumbnails in grids, cards

### 3. **Fit** (Preserve All - Add Padding)

[](#3-fit-preserve-all---add-padding)

```
// config/thumbnails.php
'method' => 'fit',
```

- ✅ Entire image visible
- ✅ Exact dimensions
- ⚠️ May have padding/borders

**Use for:** Logos, icons, images where nothing can be cut

**Visual comparison:**

```
Original: 800x600 → Target: 200x200

RESIZE:  200x150 (proportional, smaller)
CROP:    200x200 (center cropped)
FIT:     200x200 (padded top/bottom)

```

---

📚 Usage Methods
---------------

[](#-usage-methods)

### 1. Blade Directive

[](#1-blade-directive)

```

```

### 2. Facade

[](#2-facade)

```
use Moonlight\Thumbnails\Facades\Thumbnail;

$url = Thumbnail::thumbnail('photos/image.jpg', 'medium');
```

### 3. Helper Functions

[](#3-helper-functions)

```
// Get URL
$url = thumbnail('photos/image.jpg', 'small');

// Aliases
$url = thumbnail_url('photos/image.jpg', 'small');
$path = thumbnail_path('photos/image.jpg', 'small'); // Returns relative path
```

### 4. Service Injection

[](#4-service-injection)

```
use Moonlight\Thumbnails\Services\ThumbnailService;

class ImageController
{
    public function show(ThumbnailService $thumbnails)
    {
        $url = $thumbnails->thumbnail('photos/image.jpg', 'medium');
    }
}
```

### 5. JavaScript (Frontend)

[](#5-javascript-frontend)

```
import { getThumbnailUrl } from 'moonlight-thumbnails';

const thumbUrl = getThumbnailUrl('photos/cat.jpg', 'small');
// Returns: /storage/photos/thumbnails/cat_thumb_small.jpg
```

---

⚙️ Configuration
----------------

[](#️-configuration)

### Default Sizes

[](#default-sizes)

```
// config/thumbnails.php

'sizes' => [
    'small' => ['width' => 150, 'height' => 150],
    'medium' => ['width' => 300, 'height' => 300],
    'large' => ['width' => 600, 'height' => 600],

    // Add your custom sizes:
    'avatar' => ['width' => 200, 'height' => 200],
    'banner' => ['width' => 1200, 'height' => 400],
],
```

### Drivers

[](#drivers)

```
'driver' => 'gd', // 'gd' (default), 'imagick', or 'intervention'
```

**GD** (built-in, no extra dependencies)

```
'driver' => 'gd',
```

**Imagick** (better quality, requires `ext-imagick`)

```
'driver' => 'imagick',
```

**Intervention Image** (most features, requires package)

```
composer require intervention/image
```

```
'driver' => 'intervention',
```

### Quality &amp; Performance

[](#quality--performance)

```
'quality' => 85,              // JPEG quality (1-100)
'fallback_on_error' => true,  // Return original on error
'cache_control' => 'public, max-age=31536000', // 1 year cache
```

---

🎯 Advanced Features
-------------------

[](#-advanced-features)

### HasThumbnails Trait

[](#hasthumbnails-trait)

Automatically delete thumbnails when model is deleted:

```
use Moonlight\Thumbnails\Traits\HasThumbnails;

class UserPost extends Model
{
    use HasThumbnails;

    // Define which fields contain images
    protected $thumbnailFields = ['cover_image', 'gallery_image'];
}

// Usage in model
$post->thumbnail('cover_image', 'small'); // Get thumbnail URL
$post->thumbnails('cover_image'); // Get all sizes: ['small' => 'url', ...]
```

### Artisan Commands

[](#artisan-commands)

```
# Generate thumbnails for specific image
php artisan thumbnails:generate photos/image.jpg

# Generate specific size
php artisan thumbnails:generate photos/image.jpg --size=small

# Force regenerate (overwrite existing)
php artisan thumbnails:generate photos/image.jpg --force

# Clear all thumbnails
php artisan thumbnails:clear

# Clear specific directory
php artisan thumbnails:clear photos

# Clear specific image thumbnails
php artisan thumbnails:clear photos/image.jpg
```

### Manual Management

[](#manual-management)

```
use Moonlight\Thumbnails\Facades\Thumbnail;

// Delete all thumbnails for an image
Thumbnail::deleteThumbnails('photos/image.jpg');

// Clear all thumbnails in directory
Thumbnail::clearAllThumbnails('photos');

// Clear ALL thumbnails in app
Thumbnail::clearAllThumbnails();
```

---

🆕 V2.0 New Features
-------------------

[](#-v20-new-features)

### Smart Crop (AI Energy Detection)

[](#smart-crop-ai-energy-detection)

Automatically detect the most important part of the image for intelligent cropping:

```
// config/thumbnails.php
'smart_crop' => [
    'enabled' => true,
    'algorithm' => 'energy', // 'energy', 'faces', 'saliency'
    'rule_of_thirds' => true, // Align focal point to rule of thirds
],
```

**Usage:**

```
{{-- Smart crop will detect focal point automatically --}}

```

**When to use:**

- Portrait photos (focuses on face/eyes)
- Product photos (focuses on the product)
- Landscape photos (focuses on horizon/main subject)

---

### Modern Image Formats (AVIF/WebP)

[](#modern-image-formats-avifwebp)

Automatically convert thumbnails to modern formats for **50% smaller file sizes**:

```
// config/thumbnails.php
'formats' => [
    'auto_convert' => true,
    'priority' => ['avif', 'webp', 'jpg'], // Try in order
    'quality' => [
        'avif' => 85,
        'webp' => 90,
        'jpg' => 85,
    ],
],
```

**How it works:**

1. Package checks available image libraries (GD, Imagick, Intervention)
2. Selects best available format from priority list
3. Generates thumbnail in optimal format
4. Falls back to JPEG if modern formats unavailable

**Performance:**

- AVIF: ~50% smaller than JPEG (requires Imagick)
- WebP: ~30% smaller than JPEG (GD/Imagick)
- Automatic fallback ensures compatibility

---

### 🔐 Laravel Native Signed URLs Integration

[](#-laravel-native-signed-urls-integration)

**Version 2.0.18+** uses Laravel's native `URL::temporarySignedRoute()` for signed URLs instead of custom Facebook-style implementation.

### ⚙️ Required Setup (4 steps)

[](#️-required-setup-4-steps)

#### 1️⃣ **Create StorageController**

[](#1️⃣-create-storagecontroller)

Create `app/Http/Controllers/StorageController.php`:

```
