PHP code example of subhashladumor1 / laravel-translate

1. Go to this page and download the library: Download subhashladumor1/laravel-translate library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

subhashladumor1 / laravel-translate example snippets


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

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

use Subhashladumor1\Translate\Facades\Translate;

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

// 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');

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

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

$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');

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

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

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...
    }
});

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

// 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']);
});

return [
    // Default translation service (no API key ', 'lingva'),
    
    // Fallback chain - tries services in order
    // Services without API key ,
    '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,
    ],
];

'services' => [
    'argos' => [
        'enabled' => true,
        'endpoint' => 'http://localhost:5000',
    ],
],

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!']);
    }
}

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
    ]);
}

// 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('[email protected]');
    
    // Clear old cache weekly
    $schedule->command('translate:clear-cache')
             ->weekly()
             ->sundays()
             ->at('03:00');
}

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

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

Translate::detectLanguage(string $text): string

Translate::clearCache(): void

Translate::getAnalytics(): array

// ✅ 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);
}
bash
php artisan vendor:publish --tag=translate-config
bash
# 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
bash
# 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
bash
# 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
bash
php artisan cache:table
php artisan migrate
bash
php artisan translate:test --service=libre
blade
<!-- 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>
bash
php artisan config:clear
php artisan cache:clear
php artisan translate:clear-cache