subhashladumor1/laravel-translate

๐ŸŒ Professional multi-source translation package for Laravel 11+ with free APIs (LibreTranslate, Lingva, MyMemory), smart caching, batch translation, CLI tools, and analytics dashboard. Zero API costs!

Installs: 8

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/subhashladumor1/laravel-translate

1.0.3 2025-10-26 09:31 UTC

This package is auto-updated.

Last update: 2025-10-26 09:48:54 UTC


README

๐ŸŒ Laravel Translate

Professional Multi-Source Translation Package for Laravel 11+

Latest Version Laravel Version License PHP Version

Transform your Laravel application into a multilingual powerhouse with zero API costs!
Automatic fallback โ€ข Smart caching โ€ข Batch translation โ€ข Analytics dashboard โ€ข Offline support

Installation โ€ข Quick Start โ€ข Features โ€ข Documentation โ€ข Support

โœจ Why Laravel Translate?

๐ŸŽฏ Zero API Costs - Use completely free translation services (no API key needed!)
โšก Lightning Fast - Smart caching reduces API calls by 90%+
๐Ÿ”„ Bulletproof - Automatic fallback across 5 translation services
๐ŸŽจ Developer Friendly - Blade directives, helpers, facades, CLI
๐Ÿ“Š Production Ready - Built-in analytics and performance monitoring
๐ŸŒ Truly Multilingual - Support 100+ languages out of the box
๐Ÿ”Œ Offline Capable - Works without internet using Argos
๐Ÿš€ SaaS Ready - Perfect for multi-tenant applications

๐ŸŽ Features

๐Ÿ”ฅ Core Features

  • โœ… 5 Free Translation APIs
    • Lingva Translate (Default - No API Key)
    • Google Free (No API Key)
    • MyMemory (No API Key)
    • LibreTranslate (Free tier available)
    • Argos (Offline)
  • โœ… Auto Language Detection
  • โœ… Intelligent Fallback Chain
  • โœ… Batch Translation
  • โœ… Smart Caching System

๐Ÿ› ๏ธ Developer Tools

  • โœ… 5 Powerful CLI Commands
  • โœ… Blade Directives
  • โœ… Helper Functions
  • โœ… Facade Support
  • โœ… Auto-Locale Middleware
  • โœ… Queue Integration
  • โœ… Analytics Dashboard
  • โœ… Translation Logging
  • โœ… Service Testing Tool

๐Ÿ“ฆ Installation

Step 1: Install via Composer

composer require subhashladumor1/laravel-translate

Step 2: Publish Configuration (Optional)

php artisan vendor:publish --tag=translate-config

Step 3: Configure (Optional)

Add to your .env file:

# Default service (works without API key)
TRANSLATE_DEFAULT_SERVICE=lingva

# Enable caching for better performance
TRANSLATE_CACHE_ENABLED=true
TRANSLATE_CACHE_DRIVER=redis
TRANSLATE_CACHE_TTL=86400

# Optional: Enable LibreTranslate with API key
# Get free key at https://portal.libretranslate.com
TRANSLATE_LIBRE_ENABLED=false
TRANSLATE_LIBRE_API_KEY=your-api-key-here

That's it! ๐ŸŽ‰ The package works out-of-the-box with 3 services (Lingva, Google, MyMemory) - no API key required!

๐Ÿš€ Quick Start

๐Ÿ’ก Translate in 3 Ways

1๏ธโƒฃ Using Helper Function

// Simple translation
echo translateText('Hello World', 'es');
// Output: Hola Mundo

// With auto-detection
echo translate('Bonjour', 'en');
// Output: Hello

2๏ธโƒฃ Using Facade

use Subhashladumor1\Translate\Facades\Translate;

$translation = Translate::translate('Good morning', 'fr');
// Output: Bonjour

3๏ธโƒฃ In Blade Templates

<!-- Simple translation -->
<h1>@translate('Welcome to our site', 'es')</h1>

<!-- Block translation -->
@translateStart('de')
    This entire block will be translated to German.
    Multiple sentences are supported!
@translateEnd

<!-- Dynamic locale -->
<p>{{ translateText('Thank you', app()->getLocale()) }}</p>

๐Ÿ“– Complete Documentation

๐ŸŽฏ Basic Usage

Translate Text

// Basic translation
$spanish = Translate::translate('Hello', 'es');

// Specify source language
$french = Translate::translate('Hello', 'fr', 'en');

// Auto-detect source
$result = Translate::translate('Hola', 'en', 'auto');

Detect Language

$lang = Translate::detectLanguage('Bonjour le monde');
// Returns: 'fr'

// In Blade
<span>Language: @detectLang($userText)</span>

Batch Translation

$texts = ['Hello', 'Goodbye', 'Thank you'];
$translations = Translate::translateBatch($texts, 'it');
// Returns: ['Ciao', 'Arrivederci', 'Grazie']

// Translate arrays
$data = [
    'title' => 'Welcome',
    'message' => 'Hello World',
    'items' => ['One', 'Two', 'Three']
];

$translated = app('translator')->translateArray($data, 'es');

๐ŸŽจ Blade Directives

@translate Directive

<!-- Simple usage -->
<h1>@translate('Hello', 'es')</h1>

<!-- With variables -->
<p>@translate($product->name, $userLanguage)</p>

<!-- Navigation example -->
<nav>
    <a href="/">@translate('Home', app()->getLocale())</a>
    <a href="/about">@translate('About Us', app()->getLocale())</a>
    <a href="/contact">@translate('Contact', app()->getLocale())</a>
</nav>

Block Translation

@translateStart('fr')
    We offer the best services in the industry.
    Our team is dedicated to providing excellent customer support.
    Contact us today to learn more about our offerings!
@translateEnd

Forms with Translation

<form>
    <label>@translate('Full Name', $locale)</label>
    <input type="text" placeholder="@translate('Enter your name', $locale)">
    
    <label>@translate('Email Address', $locale)</label>
    <input type="email" placeholder="@translate('your@email.com', $locale)">
    
    <button>@translate('Submit', $locale)</button>
</form>

๐Ÿ”ง CLI Commands

1. Test Services

# Test all translation services
php artisan translate:test

# Test specific service
php artisan translate:test --service=lingva

# Custom text and language
php artisan translate:test --text="Good morning" --target=fr

This command helps you:

  • โœ… Verify which services are working
  • โœ… Check API response times
  • โœ… Diagnose connection issues
  • โœ… See translation quality

2. Translate String

# Basic usage
php artisan translate:string "Hello World" es
# Output: Hola Mundo

# Specify source language
php artisan translate:string "Bonjour" en --source=fr
# Output: Hello

3. Translate Files

# Translate Laravel language file
php artisan translate:file resources/lang/en/messages.php es

# Custom output path
php artisan translate:file resources/lang/en/auth.php fr --output=lang/fr/auth.php

# Export as JSON
php artisan translate:file resources/lang/en/validation.php de --format=json

4. Sync Translations

# Sync to multiple languages
php artisan translate:sync --source=en --target=es,fr,de

# Force overwrite existing translations
php artisan translate:sync --source=en --target=es --force

# Custom language directory
php artisan translate:sync --source=en --target=fr --path=lang

5. Clear Cache

# Clear translation cache
php artisan translate:clear-cache

# Also clear analytics
php artisan translate:clear-cache --analytics

๐ŸŽฏ Advanced Features

Middleware - Auto Locale Detection

Register the middleware in your Laravel app:

// In bootstrap/app.php (Laravel 11)
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'detect.locale' => \Subhashladumor1\Translate\Http\Middleware\DetectLocale::class,
    ]);
})

Apply to routes:

Route::middleware(['detect.locale'])->group(function () {
    Route::get('/', [HomeController::class, 'index']);
    Route::get('/products', [ProductController::class, 'index']);
});

The middleware automatically detects locale from:

  1. URL query parameter (?lang=es)
  2. User session
  3. Authenticated user's language preference
  4. Browser Accept-Language header
  5. GeoIP (optional)

Queue Integration

For large translation jobs:

use Illuminate\Support\Facades\Queue;

Queue::push(function() {
    $products = Product::all();
    
    foreach ($products as $product) {
        $translations = Translate::translateBatch([
            $product->name,
            $product->description
        ], 'es');
        
        // Save translations...
    }
});

Configure queue settings in config/translate.php:

'queue' => [
    'enabled' => true,
    'connection' => 'redis',
    'queue' => 'translations',
],

๐Ÿ“Š Analytics Dashboard

Access the beautiful analytics dashboard:

http://your-app.test/translate/dashboard

Monitor:

  • ๐Ÿ“ˆ Cache hit/miss rates
  • โšก API latency per service
  • ๐Ÿ“ Recent translation logs
  • ๐ŸŽฏ Service performance comparison
  • ๐Ÿ’พ Storage efficiency

Protect the dashboard (recommended):

// In routes/web.php or RouteServiceProvider
Route::middleware(['web', 'auth', 'can:view-analytics'])->group(function () {
    Route::get('/translate/dashboard', [\Subhashladumor1\Translate\Http\Controllers\DashboardController::class, 'index']);
});

โš™๏ธ Configuration

Service Configuration

Edit config/translate.php:

return [
    // Default translation service (no API key required)
    'default_service' => env('TRANSLATE_DEFAULT_SERVICE', 'lingva'),
    
    // Fallback chain - tries services in order
    // Services without API key requirements are prioritized
    'fallback_chain' => ['lingva', 'google', 'mymemory', 'libre'],
    
    // Default languages
    'source_lang' => env('TRANSLATE_SOURCE_LANG', 'auto'),
    'target_lang' => env('TRANSLATE_TARGET_LANG', 'en'),
    'fallback_lang' => env('TRANSLATE_FALLBACK_LANG', 'en'),
    
    // Cache configuration
    'cache' => [
        'enabled' => env('TRANSLATE_CACHE_ENABLED', true),
        'driver' => env('TRANSLATE_CACHE_DRIVER', 'file'), // file, redis, database
        'ttl' => env('TRANSLATE_CACHE_TTL', 86400), // 24 hours
        'prefix' => 'translate',
        'auto_invalidate' => true,
    ],
    
    // Service endpoints
    'services' => [
        'libre' => [
            'enabled' => env('TRANSLATE_LIBRE_ENABLED', false), // Requires API key
            'endpoint' => 'https://libretranslate.com',
            'api_key' => env('TRANSLATE_LIBRE_API_KEY', null), // Get free key at https://portal.libretranslate.com
            'timeout' => 15,
        ],
        'lingva' => [
            'enabled' => env('TRANSLATE_LINGVA_ENABLED', true), // No API key needed
            'endpoint' => 'https://lingva.ml',
            'timeout' => 15,
        ],
        'google' => [
            'enabled' => env('TRANSLATE_GOOGLE_ENABLED', true), // No API key needed
            'endpoint' => 'https://translate.googleapis.com',
            'timeout' => 15,
        ],
        'mymemory' => [
            'enabled' => env('TRANSLATE_MYMEMORY_ENABLED', true), // No API key needed
            'endpoint' => 'https://api.mymemory.translated.net',
            'email' => env('TRANSLATE_MYMEMORY_EMAIL', null), // Optional for higher limits
            'timeout' => 15,
        ],
        // ... more services
    ],
    
    // Analytics
    'analytics' => [
        'enabled' => env('TRANSLATE_ANALYTICS_ENABLED', true),
        'track_cache_hits' => true,
        'track_api_latency' => true,
        'log_translations' => env('TRANSLATE_LOG_TRANSLATIONS', false),
        'retention_days' => 30,
    ],
];

Cache Drivers

For Production (Redis - Recommended):

TRANSLATE_CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

For Development (File):

TRANSLATE_CACHE_DRIVER=file

For Database:

php artisan cache:table
php artisan migrate
TRANSLATE_CACHE_DRIVER=database

๐ŸŒ Supported Translation Services

Service Speed Quality API Key Offline Rate Limit Status
๐ŸŸข Lingva โšกโšกโšกโšก โญโญโญโญ โŒ No โŒ Generous โœ… Default
๐ŸŸข Google Free โšกโšกโšกโšกโšก โญโญโญโญโญ โŒ No โŒ Good โœ… Active
๐ŸŸก MyMemory โšกโšก โญโญโญ โŒ No โŒ 1000/day โœ… Active
๐ŸŸก LibreTranslate โšกโšกโšก โญโญโญโญ โš ๏ธ Required โŒ 100K/mo free โš™๏ธ Optional
๐ŸŸข Argos โšกโšกโšก โญโญโญ โŒ No โœ… Unlimited โš™๏ธ Optional

Legend: โšก = Fast | โญ = Quality Rating

Important Notes:

  • Lingva, Google, MyMemory: Work out-of-the-box, no API key required
  • LibreTranslate: Now requires free API key from portal.libretranslate.com
  • Argos: Self-hosted, offline translation (requires installation)

๐Ÿ”‘ LibreTranslate API Key Setup (Optional)

LibreTranslate now requires an API key. Get one for FREE (100,000 characters/month):

Step 1: Get Free API Key

  1. Visit https://portal.libretranslate.com
  2. Sign up (no credit card required)
  3. Get your API key from dashboard

Step 2: Configure Laravel

Add to .env:

TRANSLATE_LIBRE_ENABLED=true
TRANSLATE_LIBRE_API_KEY=your-api-key-here

Step 3: Test

php artisan translate:test --service=libre

Alternative: Self-Host LibreTranslate

# Run locally with Docker (no API key needed)
docker run -d -p 5000:5000 libretranslate/libretranslate

Then configure:

TRANSLATE_LIBRE_ENABLED=true
TRANSLATE_LIBRE_ENDPOINT=http://localhost:5000
# No API key needed for self-hosted

๐Ÿ”Œ Offline Translation (Argos)

Setup Argos Translate for offline use:

  1. Install Argos:
pip install argostranslate
  1. Run Argos server:
argos-translate --host 0.0.0.0 --port 5000
  1. Enable in config:
'services' => [
    'argos' => [
        'enabled' => true,
        'endpoint' => 'http://localhost:5000',
    ],
],

Perfect for:

  • Air-gapped environments
  • Privacy-sensitive applications
  • No internet dependency
  • Unlimited translations

๐Ÿ’ผ Real-World Examples

E-commerce Product Translation

namespace App\Http\Controllers;

use App\Models\Product;
use Subhashladumor1\Translate\Facades\Translate;

class ProductController extends Controller
{
    public function translateProducts()
    {
        $products = Product::all();
        $targetLanguages = ['es', 'fr', 'de', 'it'];
        
        foreach ($products as $product) {
            foreach ($targetLanguages as $lang) {
                ProductTranslation::updateOrCreate([
                    'product_id' => $product->id,
                    'language' => $lang,
                ], [
                    'name' => translateText($product->name, $lang),
                    'description' => translateText($product->description, $lang),
                    'features' => translate_array($product->features, $lang),
                ]);
            }
        }
        
        return response()->json(['message' => 'Products translated!']);
    }
}

Multi-Language Blog

<!-- resources/views/blog/post.blade.php -->
<article>
    <h1>{{ translateText($post->title, app()->getLocale()) }}</h1>
    
    <div class="meta">
        <span>{{ translateText('Published on', app()->getLocale()) }}: {{ $post->published_at }}</span>
        <span>{{ translateText('By', app()->getLocale()) }} {{ $post->author }}</span>
    </div>
    
    <div class="content">
        @translateStart(app()->getLocale())
            {!! $post->content !!}
        @translateEnd
    </div>
    
    <div class="tags">
        <strong>{{ translateText('Tags', app()->getLocale()) }}:</strong>
        @foreach($post->tags as $tag)
            <span class="tag">{{ translateText($tag, app()->getLocale()) }}</span>
        @endforeach
    </div>
</article>

Dynamic Contact Form

public function sendContactForm(Request $request)
{
    $userLang = $request->user()->preferred_language ?? 'en';
    
    // Send confirmation in user's language
    $confirmationMessage = translateText(
        'Thank you for contacting us! We will respond within 24 hours.',
        $userLang
    );
    
    // Send notification to admin in default language
    $adminNotification = translateText(
        'New contact form submission from {name}',
        config('app.locale')
    );
    
    return response()->json([
        'message' => $confirmationMessage
    ]);
}

Automated Language File Sync

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    // Auto-sync translations daily at 2 AM
    $schedule->command('translate:sync --source=en --target=es,fr,de')
             ->dailyAt('02:00')
             ->emailOutputOnFailure('admin@example.com');
    
    // Clear old cache weekly
    $schedule->command('translate:clear-cache')
             ->weekly()
             ->sundays()
             ->at('03:00');
}

๐ŸŽ“ API Reference

Facade Methods

Translate::translate()

Translate::translate(string $text, ?string $targetLang = null, string $sourceLang = 'auto'): string

Translates text to the target language.

Translate::translateBatch()

Translate::translateBatch(array $texts, ?string $targetLang = null, string $sourceLang = 'auto'): array

Translates multiple texts at once.

Translate::detectLanguage()

Translate::detectLanguage(string $text): string

Detects the language of given text.

Translate::clearCache()

Translate::clearCache(): void

Clears all translation cache.

Translate::getAnalytics()

Translate::getAnalytics(): array

Returns analytics data including cache stats and latency.

Helper Functions

Function Description Example
translateText() Translate text translateText('Hello', 'es')
translate() Full translation translate('Hello', 'fr')
translate_batch() Batch translate translate_batch(['Hi', 'Bye'], 'de')
detect_language() Detect language detect_language('Bonjour')
translate_array() Array translation translate_array($data, 'es')

Blade Directives

Directive Usage Example
@translate Inline translation @translate('Welcome', 'es')
@translateStart/@translateEnd Block translation @translateStart('fr') ... @translateEnd
@detectLang Detect language @detectLang($text)

Artisan Commands

Command Description
translate:test Test all translation services
translate:string {text} {target} Translate a string
translate:file {source} {target} Translate entire file
translate:sync --source=en --target=es,fr Sync translations
translate:clear-cache Clear cache

๐ŸŽฏ Supported Languages

100+ languages supported including:

ar Arabic โ€ข bn Bengali โ€ข zh Chinese โ€ข cs Czech โ€ข da Danish โ€ข nl Dutch โ€ข en English โ€ข fi Finnish โ€ข fr French โ€ข de German โ€ข el Greek โ€ข he Hebrew โ€ข hi Hindi โ€ข hu Hungarian โ€ข id Indonesian โ€ข it Italian โ€ข ja Japanese โ€ข ko Korean โ€ข ms Malay โ€ข no Norwegian โ€ข pl Polish โ€ข pt Portuguese โ€ข ro Romanian โ€ข ru Russian โ€ข es Spanish โ€ข sv Swedish โ€ข th Thai โ€ข tr Turkish โ€ข uk Ukrainian โ€ข ur Urdu โ€ข vi Vietnamese

And many more! Check service documentation for complete list.

๐Ÿ“Š Performance & Benchmarks

Translation Speed

Operation Without Cache With Cache Improvement
Single Translation ~150ms ~1ms 150x faster
Batch (50 items) ~3000ms ~50ms 60x faster
File Translation ~5000ms ~100ms 50x faster

Cache Hit Rates

In production environments with proper caching:

  • ๐Ÿ“ˆ Average cache hit rate: 85-95%
  • โšก Average response time: 2-5ms
  • ๐Ÿ’พ Storage overhead: Minimal

๐Ÿ›ก๏ธ Security

Best Practices

// โœ… GOOD - Sanitize input
$cleanText = strip_tags($userInput);
$translation = Translate::translate($cleanText, 'es');

// โŒ BAD - Direct user input
$translation = Translate::translate($_POST['text'], 'es');

// โœ… GOOD - Rate limiting
use Illuminate\Support\Facades\RateLimiter;

if (RateLimiter::tooManyAttempts('translate:'.$request->ip(), 60)) {
    abort(429);
}

Data Privacy

  • โš ๏ธ Text is sent to third-party APIs
  • โœ… No data stored on our servers
  • โœ… HTTPS encryption for all requests
  • โœ… Use Argos for sensitive data (offline)
  • โœ… Cache can be encrypted

๐Ÿค Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

Quick Contribution Steps

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

๐Ÿ†˜ Troubleshooting

LibreTranslate API Key Error?

If you see: "Visit https://portal.libretranslate.com to get an API key"

Solution 1: Use services that don't require API key (Default)

# Package now uses Lingva by default (no API key needed)
php artisan translate:test
# Should show Lingva, Google, MyMemory working

Solution 2: Get free LibreTranslate API key

  1. Visit https://portal.libretranslate.com
  2. Sign up (100,000 characters/month FREE)
  3. Add to .env:
TRANSLATE_LIBRE_ENABLED=true
TRANSLATE_LIBRE_API_KEY=your-api-key-here

Solution 3: Self-host LibreTranslate

docker run -d -p 5000:5000 libretranslate/libretranslate
TRANSLATE_LIBRE_ENDPOINT=http://localhost:5000

Translations not working?

  1. Test services: php artisan translate:test
  2. Check internet connectivity
  3. Verify services are enabled in config
  4. Clear cache: php artisan translate:clear-cache
  5. Check logs: storage/logs/laravel.log

Cache not working?

php artisan config:clear
php artisan cache:clear
php artisan translate:clear-cache

Dashboard not accessible?

Make sure routes are loaded and middleware is not blocking access.

Need Help?

๐Ÿ“œ License

This package is open-sourced software licensed under the MIT license.

๐Ÿ’– Credits

  • Author: Subhash Ladumor
  • Translation APIs: LibreTranslate, Lingva, MyMemory, Google, Argos
  • Community: All our amazing contributors

โญ Show Your Support

If you find this package helpful, please consider:

  • โญ Starring the repository
  • ๐Ÿฆ Sharing on social media
  • ๐Ÿ“ Writing a blog post
  • ๐Ÿ’ฌ Telling your friends

๐ŸŒŸ Made with โค๏ธ for the Laravel Community

Documentation โ€ข Examples โ€ข Contributing โ€ข License

Ready to make your Laravel app multilingual? Install now and start translating! ๐Ÿš€

composer require subhashladumor1/laravel-translate