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

Translations Laravel Package

becklyn/translations

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require becklyn/translations
    

    Add to config/bundles.php (if using Symfony):

    return [
        // ...
        Becklyn\TranslationsBundle\BecklynTranslationsBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Add to config/packages/becklyn_translations.yaml:

    becklyn_translations:
        cache_version: 1
    
  3. First Use Case

    • Define extraction rules in config/packages/becklyn_translations.yaml:
      becklyn_translations:
          extract:
              frontend:
                  messages:
                      - app.*
                      - auth.*
      
    • Run the extraction command:
      php bin/console becklyn:translations:extract
      
    • Include the generated JS in your frontend:
      <script src="{{ asset('_v/translations/frontend.js') }}"></script>
      
    • Initialize translations in JS:
      window.translations = window.translations || {};
      window.translations.init('frontend', translations);
      

Implementation Patterns

Workflows

  1. Translation Extraction

    • Use the CLI command to extract translations from PHP files:
      php bin/console becklyn:translations:extract
      
    • Schedule this command in a post-update-cmd in composer.json for CI/CD pipelines:
      "scripts": {
          "post-update-cmd": [
              "@php bin/console becklyn:translations:extract"
          ]
      }
      
  2. Namespacing Translations

    • Organize translations by context (e.g., frontend, admin):
      becklyn_translations:
          extract:
              frontend:
                  messages: [app.*, auth.*]
              admin:
                  messages: [admin.*, settings.*]
      
    • Load translations dynamically in JS:
      // Load frontend translations
      translations.init('frontend', translationsFrontend);
      
      // Load admin translations (if needed)
      translations.init('admin', translationsAdmin);
      
  3. Integration with Frontend Frameworks

    • Vue.js: Bind translations to a Vuex store or composable:
      import { useTranslations } from '@/composables/translations';
      
      const { t } = useTranslations('frontend');
      
    • React: Use a context provider:
      const TranslationContext = createContext();
      // Wrap app with <TranslationContext.Provider value={translations}>
      
  4. Dynamic Translation Updates

    • Invalidate cache when translations change:
      php bin/console becklyn:translations:invalidate-cache
      
    • Or bump cache_version in config and redeploy.

Integration Tips

  1. Laravel-Specific Setup

    • Publish config for customization:
      php artisan vendor:publish --provider="Becklyn\TranslationsBundle\BecklynTranslationsBundle" --tag="config"
      
    • Override default routes in routes/web.php:
      Route::get('_v/translations/{namespace}.js', \Becklyn\TranslationsBundle\Controller\TranslationController::class)
          ->where('namespace', 'frontend|admin');
      
  2. Custom Extraction Logic

    • Extend the extractor service by binding your own implementation:
      $this->app->bind(
          \Becklyn\TranslationsBundle\Extractor\ExtractorInterface::class,
          \App\Services\CustomExtractor::class
      );
      
  3. Localization with JavaScript

    • Use libraries like i18next alongside the bundle:
      i18next.init({
          resources: {
              en: { translation: translations }
          }
      });
      
  4. Testing

    • Mock translations in PHPUnit:
      $this->app->instance(
          \Becklyn\TranslationsBundle\Loader\TranslationLoaderInterface::class,
          new \App\Tests\MockTranslationLoader()
      );
      

Gotchas and Tips

Pitfalls

  1. Cache Invalidation

    • Forgetting to bump cache_version after manual translation edits will serve stale JS.
    • Fix: Automate cache invalidation in deployment scripts or use a post-save hook in your CMS.
  2. Wildcard Overuse

    • Overly broad patterns (e.g., *.*) may extract unused translations, bloating JS bundles.
    • Fix: Scope patterns tightly (e.g., auth.* instead of *.*).
  3. Namespace Collisions

    • Reusing namespaces (e.g., frontend for both PHP and JS) can cause confusion.
    • Fix: Use descriptive names (e.g., frontend-php, frontend-js).
  4. Route Conflicts

    • Default routes (/_v/translations/) may clash with existing routes.
    • Fix: Customize the route prefix in config/packages/becklyn_translations.yaml:
      _import.becklyn_translations:
          resource: '@BecklynTranslationsBundle/Resources/config/routes.yaml'
          prefix: /assets/translations/
      

Debugging

  1. Missing Translations

    • Check if the extraction command ran successfully:
      php bin/console becklyn:translations:extract --verbose
      
    • Verify the config matches your translation keys (e.g., app.welcome vs. app.*).
  2. JS Not Loading

    • Ensure the route is accessible:
      curl http://localhost/_v/translations/frontend.js
      
    • Check browser dev tools for 404 errors or failed requests.
  3. Cache Issues

    • Clear Laravel cache:
      php artisan cache:clear
      php artisan config:clear
      
    • Manually delete cached files in var/cache/dev/ (or bootstrap/cache/ in Laravel).

Tips

  1. Versioning

    • Use semantic versioning for cache_version (e.g., 1.0.0 for major updates, 1.0.1 for minor fixes).
  2. Environment-Specific Configs

    • Override extraction rules per environment:
      # config/packages/becklyn_translations_{env}.yaml
      becklyn_translations:
          extract:
              frontend:
                  messages: [app.%, auth.*]  # % = current env
      
  3. Performance

    • Exclude unused languages from extraction:
      becklyn_translations:
          extract:
              frontend:
                  locales: [en, fr]  # Only extract for these locales
      
  4. Extending Functionality

    • Add custom filters to the extractor:
      // app/Extractor/CustomFilter.php
      public function filter(array $messages): array {
          return array_filter($messages, fn($key) => str_contains($key, 'custom.'));
      }
      
    • Bind the filter in AppServiceProvider:
      $this->app->make(\Becklyn\TranslationsBundle\Extractor\Extractor::class)
          ->addFilter(new \App\Extractor\CustomFilter());
      
  5. Local Development

    • Disable caching in config/packages/becklyn_translations.yaml:
      becklyn_translations:
          cache_version: dev  # Forces cache busting
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware