PHPackages                             masum/laravel-ai-translator - 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. [Localization &amp; i18n](/categories/localization)
4. /
5. masum/laravel-ai-translator

ActiveLibrary[Localization &amp; i18n](/categories/localization)

masum/laravel-ai-translator
===========================

AI-powered Laravel translation package with Gemini API integration, smart caching, and automatic translation management

v1.0.3(today)07MITPHPPHP ^8.2

Since May 21Pushed 1mo agoCompare

[ Source](https://github.com/MasumNishat/ai-translation)[ Packagist](https://packagist.org/packages/masum/laravel-ai-translator)[ RSS](/packages/masum-laravel-ai-translator/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (24)Versions (5)Used By (0)

Laravel AI Translator
=====================

[](#laravel-ai-translator)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b9b78c53d7b3a278aaba7b3c81dd340b69eeed4485300ef851d4ddd45a279898/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6173756d2f6c61726176656c2d61692d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/masum/laravel-ai-translator)[![Total Downloads](https://camo.githubusercontent.com/c71eb08547d01e6eee8e2e99b8a287f078c457d9f1075cb83a9d8e7033342c3d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6173756d2f6c61726176656c2d61692d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/masum/laravel-ai-translator)[![PHP Version](https://camo.githubusercontent.com/b3f407b8ba361b74e2b7994f3f5ce06bac93b4f5cdb3cd1bbd4e93efa309d25f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6d6173756d2f6c61726176656c2d61692d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/masum/laravel-ai-translator)[![License](https://camo.githubusercontent.com/264e7f5377dd6bdab471c125b2acc972f449012cb5666a9a7683ebf4b9cffef0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d6173756d2f6c61726176656c2d61692d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/masum/laravel-ai-translator)

AI-powered Laravel translation package with Google Gemini API integration, smart caching, and automatic translation management.

---

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

[](#table-of-contents)

- [Features](#features) — What the package provides at a glance
- [Requirements](#requirements) — PHP, Laravel, and API key prerequisites
- [Installation](#installation) — Step-by-step setup guide
    - [1. Install via Composer](#1-install-via-composer)
    - [2. Publish Configuration](#2-publish-configuration)
    - [3. Publish and Run Migrations](#3-publish-and-run-migrations)
    - [4. Configure Environment](#4-configure-environment)
    - [5. Add Languages](#5-add-languages)
    - [6. Register Gates (Optional)](#6-register-gates-optional)
    - [7. Add Middleware (Optional)](#7-add-middleware-optional)
- [Configuration](#configuration) — All available config options explained
- [Transparent `__()` Override](#transparent---override-zero-blade-changes) — Drop-in AI translation with no Blade changes required
- [Middleware &amp; Locale Detection](#middleware) — How language is detected, persisted, and switched per request
- [Queue Configuration](#queue-configuration) — Async translation processing with database or Redis queues
- [Rate Limiting](#rate-limiting) — Protect the Gemini API from abuse with configurable limits
- [Usage](#usage) — How to translate strings, use helpers, and integrate with models
    - [Basic Translation](#basic-translation) — `__()`, `trans()`, and `Translation::get()`
    - [Auto-Translate with AI](#auto-translate-with-ai) — Trigger AI translation on demand
    - [Helper Functions](#using-helper-functions) — Full reference of all helper functions (numbers, time, language, etc.)
    - [Using with Models](#using-with-models) — Translate model attributes automatically
- [API Reference](#api-endpoints) — RESTful endpoints for language and translation management
    - [Endpoints](#api-endpoints) — Full list of available routes
    - [Examples](#api-examples) — cURL and request examples
- [Smart Caching](#smart-caching-flow) — 3-tier caching architecture and invalidation strategy
- [Permission Gates](#permission-gates) — Control access to translation management features
- [API Key Priority](#api-key-priority) — How the Gemini API key is resolved (DB → Config → Env)
- [Audit Trail](#audit-trail) — Full history of translation changes with user tracking
- [Translation Groups](#translation-groups) — Organise translations by namespace or module
- [Artisan Commands](#artisan-commands) — Full reference for all `translator:*` commands (stats, sync, clear-cache, export, import, translate-markdown)
- [Advanced Features](#advanced-features) — Finding missing keys, clearing cache, and more
- [Building a Custom Admin UI](#building-a-custom-admin-translation-manager) — How to build your own translation manager on top of this package
- [Markdown File Translation](#markdown-file-translation) — Translate entire `.md` files (front matter + body) with one Artisan command
- [API Quota Caution](#%EF%B8%8F-api-quota-caution-free-tier) — Free tier limits, call counts, and how to stay within quota
- [Troubleshooting](#troubleshooting) — Common issues and fixes
- [Testing](#testing)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [License](#license)
- [Credits](#credits)
- [Support](#support)

---

Features
--------

[](#features)

- **Smart 3-Tier Translation Retrieval** (Cache → Database → AI)
- **Automatic AI Translation** using Google Gemini API
- **Deferred Batch Translation** — missing keys collected during request, translated in one Gemini call after response is sent (zero page-load overhead)
- **Transparent `__()` Override** — drop-in replacement for Laravel's translator, no Blade changes needed
- **Markdown File Translation** — translate entire `.md` files (front matter + body) into locale sub-directories with one Artisan command
- **Multi-Language Support** with language management
- **Smart Caching** with automatic invalidation and cache tagging
- **Queue System** for asynchronous translation processing
- **Rate Limiting** to prevent API abuse and ensure fair usage
- **API Key Priority** (Database → Config → Environment)
- **Full Audit Trail** for translation changes
- **RESTful API** for translation management
- **Laravel Gates** for permission management
- **Language to Country Mapping** API
- **Model Trait** for easy integration
- **Translation History** tracking
- **Input Sanitization** for security
- **Database Indexing** for optimized queries

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11, 12, or 13
- Google Gemini API key — get one free at [aistudio.google.com](https://aistudio.google.com)
- `google-gemini-php/laravel` package (pulled in automatically)

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require masum/laravel-ai-translator
```

### 2. Publish Configuration

[](#2-publish-configuration)

```
php artisan vendor:publish --tag=ai-translator-config
```

Also publish the Gemini Laravel config (required for the Gemini singleton to read your API key):

```
php artisan vendor:publish --provider="Gemini\Laravel\ServiceProvider"
```

### 3. Publish and Run Migrations

[](#3-publish-and-run-migrations)

```
php artisan vendor:publish --tag=ai-translator-migrations
php artisan migrate
```

### 4. Configure Environment

[](#4-configure-environment)

Add to your `.env` file:

```
# Gemini AI Configuration
GEMINI_API_KEY=your_gemini_api_key_here
GEMINI_MODEL=gemini-pro
GEMINI_TIMEOUT=30

# Cache Configuration
TRANSLATOR_CACHE_ENABLED=true
TRANSLATOR_CACHE_TTL=3600
TRANSLATOR_CACHE_PREFIX=ai_translator
TRANSLATOR_CACHE_USE_TAGS=true

# Translation Settings
TRANSLATOR_AUTO_TRANSLATE=true

# Queue Configuration (Optional - for background processing)
QUEUE_CONNECTION=redis
TRANSLATOR_QUEUE_ENABLED=true
TRANSLATOR_QUEUE_CONNECTION=redis
TRANSLATOR_QUEUE_NAME=translations
TRANSLATOR_QUEUE_BULK_NAME=translations-bulk
TRANSLATOR_QUEUE_TIMEOUT=120
TRANSLATOR_QUEUE_RETRIES=3

# Rate Limiting
TRANSLATOR_RATE_LIMIT=60
TRANSLATOR_AI_RATE_LIMIT=10
TRANSLATOR_BULK_RATE_LIMIT=5
TRANSLATOR_LANGUAGE_RATE_LIMIT=30

# Security (Optional)
TRANSLATOR_REQUIRE_AUTH=false
TRANSLATOR_ALLOW_GUEST=true
TRANSLATOR_SANITIZATION_ENABLED=true

# Locale Detection (Optional)
TRANSLATOR_PERSIST_LOCALE=true
```

### 5. Add Languages

[](#5-add-languages)

Create languages in your database:

```
use Masum\AiTranslator\Models\Language;

Language::create([
    'code' => 'en',
    'name' => 'English',
    'native_name' => 'English',
    'direction' => 'ltr',
    'is_default' => true,
    'is_active' => true,
]);

Language::create([
    'code' => 'bn',
    'name' => 'Bengali',
    'native_name' => 'বাংলা',
    'direction' => 'ltr',
    'is_active' => true,
]);
```

### 6. Register Gates (Optional)

[](#6-register-gates-optional)

In your `AuthServiceProvider.php`:

```
use Masum\AiTranslator\Gates\TranslationGates;

public function boot(): void
{
    TranslationGates::register();
}
```

### 7. Add Middleware (Optional)

[](#7-add-middleware-optional)

Register the `SetLocale` middleware in `bootstrap/app.php`. **Important:** it must be appended (not prepended) to the web group so it runs after `StartSession` — the session is not available before that.

```
use Masum\AiTranslator\Http\Middleware\SetLocale;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        SetLocale::class,
    ]);
})
```

Configuration
-------------

[](#configuration)

The package configuration file (`config/ai-translator.php`) includes:

```
return [
    // Gemini AI settings
    'gemini' => [
        'api_key' => env('GEMINI_API_KEY'),
        'model' => env('GEMINI_MODEL', 'gemini-pro'),
        'timeout' => 30,
        'max_retries' => 3,
    ],

    // Translation behavior
    'translation' => [
        'fallback_locale' => 'en',
        'cache_ttl' => 3600,
        'auto_translate_enabled' => true,
    ],

    // Queue configuration
    'queue' => [
        'enabled' => env('TRANSLATOR_QUEUE_ENABLED', true),
        'name' => env('TRANSLATOR_QUEUE_NAME', 'translations'),
        'bulk_name' => env('TRANSLATOR_QUEUE_BULK_NAME', 'translations-bulk'),
        'connection' => env('TRANSLATOR_QUEUE_CONNECTION', null),
        'timeout' => env('TRANSLATOR_QUEUE_TIMEOUT', 120),
        'retries' => env('TRANSLATOR_QUEUE_RETRIES', 3),
        'backoff' => [10, 30, 60],
    ],

    // Rate limiting
    'rate_limiting' => [
        'translations' => [
            'max_attempts' => env('TRANSLATOR_RATE_LIMIT', 60),
            'decay_seconds' => 60,
        ],
        'auto_translate' => [
            'max_attempts' => env('TRANSLATOR_AI_RATE_LIMIT', 10),
            'decay_seconds' => 60,
        ],
        'bulk' => [
            'max_attempts' => env('TRANSLATOR_BULK_RATE_LIMIT', 5),
            'decay_seconds' => 60,
        ],
        'languages' => [
            'max_attempts' => env('TRANSLATOR_LANGUAGE_RATE_LIMIT', 30),
            'decay_seconds' => 60,
        ],
    ],

    // Permission gates
    'permissions' => [
        'manage_languages' => 'manage-languages',
        'manage_translations' => 'manage-translations',
        'auto_translate' => 'auto-translate',
        'manage_settings' => 'manage-translator-settings',
    ],

    // API routes
    'routes' => [
        'enabled' => true,
        'prefix' => 'api/translator',
        'middleware' => ['api'],
    ],
];
```

Queue Configuration
-------------------

[](#queue-configuration)

The package supports asynchronous translation processing using Laravel's queue system. This improves performance by offloading expensive AI operations to background workers.

### Features

[](#features-1)

- **Asynchronous Processing** - AI translations run in the background
- **Automatic Retries** - Failed jobs retry with exponential backoff (10s, 30s, 60s)
- **Graceful Fallback** - Falls back to synchronous processing if queue fails

### Setup Queue Workers

[](#setup-queue-workers)

#### For Development (Database Queue)

[](#for-development-database-queue)

1. Create queue tables:

```
php artisan queue:table
php artisan queue:batches-table
php artisan migrate
```

2. Start queue worker:

```
php artisan queue:work --queue=translations-bulk,translations
```

#### For Production (Redis Recommended)

[](#for-production-redis-recommended)

1. Configure Redis in `.env`:

```
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
```

2. Start queue worker with recommended options:

```
php artisan queue:work redis \
    --queue=translations-bulk,translations \
    --tries=3 \
    --timeout=120 \
    --sleep=3 \
    --max-jobs=1000 \
    --max-time=3600
```

#### Supervisor Configuration (Production)

[](#supervisor-configuration-production)

Create `/etc/supervisor/conf.d/ai-translator-worker.conf`:

```
[program:ai-translator-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/your/artisan queue:work redis --queue=translations-bulk,translations --tries=3 --timeout=120 --max-jobs=1000 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/path/to/your/storage/logs/worker.log
stopwaitsecs=3600
```

Then reload Supervisor:

```
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start ai-translator-worker:*
```

### Queue Management Commands

[](#queue-management-commands)

```
# Monitor queue status
php artisan queue:monitor translations,translations-bulk

# Restart workers (after code changes)
php artisan queue:restart

# Retry failed jobs
php artisan queue:retry all

# Flush failed jobs
php artisan queue:flush
```

### Disable Queues (Process Synchronously)

[](#disable-queues-process-synchronously)

Set in `.env`:

```
TRANSLATOR_QUEUE_ENABLED=false
```

Or force synchronous processing via API:

```
POST /api/translator/auto-translate?sync=true
```

Rate Limiting
-------------

[](#rate-limiting)

The package implements rate limiting to prevent API abuse and ensure fair usage across different endpoint types.

### Rate Limit Categories

[](#rate-limit-categories)

CategoryDefault LimitDescription**Translations**60/minGeneral translation API requests**Auto-Translate**10/minAI-powered translation requests (expensive)**Languages**30/minLanguage management endpoints### Environment Configuration

[](#environment-configuration)

#### Development Settings

[](#development-settings)

```
TRANSLATOR_RATE_LIMIT=1000
TRANSLATOR_AI_RATE_LIMIT=100
TRANSLATOR_BULK_RATE_LIMIT=50
TRANSLATOR_LANGUAGE_RATE_LIMIT=300
```

#### Production (Low Traffic)

[](#production-low-traffic)

```
TRANSLATOR_RATE_LIMIT=60
TRANSLATOR_AI_RATE_LIMIT=10
TRANSLATOR_BULK_RATE_LIMIT=5
TRANSLATOR_LANGUAGE_RATE_LIMIT=30
```

#### Production (High Traffic)

[](#production-high-traffic)

```
TRANSLATOR_RATE_LIMIT=120
TRANSLATOR_AI_RATE_LIMIT=20
TRANSLATOR_BULK_RATE_LIMIT=10
TRANSLATOR_LANGUAGE_RATE_LIMIT=60
```

#### Enterprise

[](#enterprise)

```
TRANSLATOR_RATE_LIMIT=300
TRANSLATOR_AI_RATE_LIMIT=50
TRANSLATOR_BULK_RATE_LIMIT=25
TRANSLATOR_LANGUAGE_RATE_LIMIT=150
```

### Rate Limit Response

[](#rate-limit-response)

When rate limit is exceeded, API returns:

```
{
  "message": "Too Many Requests",
  "status": 429,
  "retry_after": 60
}
```

### Monitoring Rate Limits

[](#monitoring-rate-limits)

Check logs for rate limit hits:

```
tail -f storage/logs/laravel.log | grep "rate_limit"
```

Transparent `__()` Override (Zero Blade Changes)
------------------------------------------------

[](#transparent-__-override-zero-blade-changes)

The recommended integration for existing Laravel applications is to override Laravel's built-in `__()` helper transparently via a custom translator class. This means **no changes to any Blade view** — all existing `__()`, `trans()`, and `@lang()` calls automatically go through the AI pipeline.

Missing translations are **collected in a static list during the request** and batch-translated in a single Gemini API call after the response is sent — so the current page load is never slowed down and the next page load is fully translated.

### 1. Create the Custom Translator

[](#1-create-the-custom-translator)

Create `app/Translation/AiTranslator.php`:

```
