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
Requires
- php: ^8.1|^8.2|^8.3
- guzzlehttp/guzzle: ^7.0
- illuminate/cache: ^9.0|^10.0|^11.0|^12.0
- illuminate/database: ^9.0|^10.0|^11.0|^12.0
- illuminate/http: ^9.0|^10.0|^11.0|^12.0
- illuminate/session: ^9.0|^10.0|^11.0|^12.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
- illuminate/view: ^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- laravel/pint: ^1.0
- orchestra/testbench: ^9.0
- phpunit/phpunit: ^9.0|^10.0|^11.0|^12.0
README
๐ Laravel Translate
Professional Multi-Source Translation Package for Laravel 11+
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
๐ฆ 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:
- URL query parameter (
?lang=es) - User session
- Authenticated user's language preference
- Browser Accept-Language header
- 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
- Visit https://portal.libretranslate.com
- Sign up (no credit card required)
- 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:
- Install Argos:
pip install argostranslate
- Run Argos server:
argos-translate --host 0.0.0.0 --port 5000
- 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
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Write tests for your changes
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- Visit https://portal.libretranslate.com
- Sign up (100,000 characters/month FREE)
- 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?
- Test services:
php artisan translate:test - Check internet connectivity
- Verify services are enabled in config
- Clear cache:
php artisan translate:clear-cache - 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?
- ๐ Read the documentation above
- ๐ Report bugs
- ๐ฌ Ask questions
- ๐ง Email: subhashladumor1@gmail.com
๐ 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