Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Symfony Bundle Laravel Package

php-translation/symfony-bundle

Symfony bundle for the PHP Translation library. Integrates translation management, storage, and workflows into Symfony apps, with services and console tooling to import/export translations and keep locale files in sync across providers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require php-translation/symfony-bundle
    

    Enable it in config/bundles.php (Symfony) or config/app.php (Laravel via Symfony bridge):

    return [
        // ...
        PhpTranslation\SymfonyBundle\PhpTranslationBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config (if needed):

    php artisan vendor:publish --provider="PhpTranslation\SymfonyBundle\PhpTranslationBundle" --tag="config"
    

    Update config/php_translation.php to define:

    • locales (e.g., ['en', 'fr'])
    • default_locale
    • paths (where translation files are stored, e.g., resources/lang).
  3. First Translation Create a translation file (e.g., resources/lang/fr/messages.php):

    return [
        'welcome' => 'Bienvenue',
    ];
    

    Use it in a controller or Blade:

    $this->translator->trans('messages.welcome');
    

First Use Case: Localized Routes

Define locale-aware routes in routes/web.php:

Route::get('/{locale}/home', function () {
    return $this->translator->trans('messages.home');
})->middleware('locale');

Use the locale middleware to set the current locale dynamically.


Implementation Patterns

1. Translation Workflows

a. Dynamic Translations

Use the translator service to fetch translations dynamically:

// In a controller
$greeting = $this->translator->trans('messages.greeting', [
    '%name%' => $user->name,
]);

Blade Integration:

{{ trans('messages.greeting', ['%name%' => $user->name]) }}

b. Fallback Locales

Configure fallback locales in config/php_translation.php:

'fallbacks' => [
    'fr' => ['en'],
    'es' => ['en'],
],

If fr translations are missing, it falls back to en.


2. Integration with Laravel

a. Service Provider Binding

Bind the Symfony translator to Laravel’s container in AppServiceProvider:

public function register()
{
    $this->app->singleton(\Symfony\Contracts\Translation\TranslatorInterface::class,
        function ($app) {
            return $this->app->make(\PhpTranslation\SymfonyBundle\PhpTranslationBundle::class)
                ->getTranslator();
        }
    );
}

b. Middleware for Locale Switching

Create middleware to set the locale from:

  • URL parameter (/fr/home)
  • Session
  • Header (Accept-Language)

Example middleware:

public function handle($request, Closure $next)
{
    $locale = $request->segment(1) ?? config('app.locale');
    app()->setLocale($locale);
    return $next($request);
}

3. Validation Messages

Extend Laravel’s validator with translated messages:

$validator = Validator::make($data, [
    'email' => 'required|email',
], [
    'email.required' => trans('validation.required', ['attribute' => 'Email']),
]);

4. API Responses

Return translated errors in API responses:

return response()->json([
    'error' => trans('errors.validation_failed'),
    'details' => $validator->errors()->toArray(),
], 422);

Gotchas and Tips

1. Common Pitfalls

a. Caching Issues

  • Problem: Translations aren’t updating after changes.
  • Fix: Clear the cache:
    php artisan cache:clear
    php artisan config:clear
    
  • Tip: Use php artisan translation:dump to regenerate translation files.

b. Locale Not Persisting

  • Problem: Locale resets after a request.
  • Fix: Store the locale in the session:
    session()->put('locale', $locale);
    
    Retrieve it in middleware:
    $locale = session('locale', config('app.locale'));
    

c. Missing Translation Files

  • Problem: trans() returns the key instead of a value.
  • Fix:
    • Ensure files exist in resources/lang/{locale}/.
    • Check for typos in translation keys.
    • Verify paths in config/php_translation.php.

2. Debugging Tips

a. Dump Available Locales

dd($this->translator->getLocator()->getLocales());

b. Check Loaded Translations

dd($this->translator->getCatalogue()->all());

c. Enable Debug Mode

Set debug: true in config/php_translation.php to log missing translations.


3. Extension Points

a. Custom Loaders

Extend the bundle to load translations from:

  • Databases
  • APIs
  • External services

Example loader:

use PhpTranslation\Loader\LoaderInterface;

class ApiTranslationLoader implements LoaderInterface
{
    public function load($locale, $domain, $theme = null)
    {
        $translations = $this->fetchFromApi($locale);
        return new \Symfony\Component\Translation\MessageCatalogue($locale, $translations);
    }
}

Register it in config/php_translation.php:

'loaders' => [
    'api' => ApiTranslationLoader::class,
],

b. Custom Domains

Use domains to organize translations (e.g., validation, errors):

$this->translator->trans('validation.required', [], 'validation');

c. Pluralization Rules

Override pluralization rules for languages like Arabic or Russian:

'pluralization_rules' => [
    'ar' => \Symfony\Component\Translation\PluralizationRules::createArabicRules(),
],

4. Performance Tips

a. Preload Translations

Preload translations for all locales in a service provider:

public function boot()
{
    $translator = $this->app->make(\Symfony\Contracts\Translation\TranslatorInterface::class);
    foreach (config('php_translation.locales') as $locale) {
        $translator->getCatalogue($locale);
    }
}

b. Use transChoice for Plurals

$message = trans_choice('messages.item', $count, [
    '%count%' => $count,
]);

5. Testing

a. Mock the Translator

$translator = Mockery::mock(\Symfony\Contracts\Translation\TranslatorInterface::class);
$translator->shouldReceive('trans')->andReturn('Mocked translation');

$this->app->instance(\Symfony\Contracts\Translation\TranslatorInterface::class, $translator);

b. Test Locale Switching

$response = $this->get('/fr/home');
$response->assertSee('Bienvenue');
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui