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

Laratext Laravel Package

edulazaro/laratext

Laratext manages and auto-translates Laravel text strings by using both key and text for readable, stable translations. Includes @text directive and text() helper, scans/updates language files, and supports OpenAI, Google Translate, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require edulazaro/laratext
    php artisan vendor:publish --tag="texts"
    
  2. Configure API keys in .env (e.g., OPENAI_API_KEY) and set supported languages in config/texts.php.
  3. First use case: Replace a hardcoded string in Blade/PHP with:
    @text('welcome.message', 'Welcome to our platform!')
    
    or in PHP:
    text('welcome.message', 'Welcome to our platform!');
    

Where to Look First

  • Blade directives: @text('key') for views.
  • Helper function: text('key', 'default') in PHP.
  • Auto-generated text: text('user.profile') → "Profile" (no default needed).
  • Command: php artisan laratext:scan --write to auto-translate missing keys.

Implementation Patterns

Core Workflows

  1. Translation Key Management:

    • Use dot notation for nested keys (e.g., auth.login.failed).
    • Leverage auto-generated text for quick prototyping (e.g., @text('user.name') → "Name").
    • Store default values in the second argument of text()/@text for fallback.
  2. Placeholder Handling:

    • Use :placeholder syntax (e.g., @text('greeting', 'Hello, :name!', ['name' => $user->name])).
    • Placeholders are preserved during translation (e.g., Spanish: "¡Hola, :nombre!").
  3. Scanning and Syncing:

    • Daily/Dev Workflow:
      php artisan laratext:scan --write  # Auto-translates new/drifted keys
      
    • Pre-Release:
      php artisan laratext:scan --write --prune  # Cleans orphaned keys
      
    • Model/Translator Change:
      php artisan laratext:scan --write --resync  # Full retranslation
      
  4. Multi-Language Support:

    • Configure languages in config/texts.php (e.g., ['es' => 'Spanish']).
    • Use the --lang=es flag to target specific languages during scans.

Integration Tips

  • Blade Directives: Prefer @text in views for readability.
  • PHP Helpers: Use text() in controllers/services for dynamic logic.
  • Fallback Logic: Always provide a default value to avoid runtime errors:
    text('key.that.might.miss', 'Default fallback text');
    
  • Testing: Mock the TranslatorInterface in unit tests to avoid API calls:
    $this->app->instance(
        \EduLazaro\Laratext\Contracts\TranslatorInterface::class,
        MockTranslator::class
    );
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits:

    • OpenAI/Google translators have request limits. Monitor usage in config/texts.php (e.g., retries, timeout).
    • Tip: Use --only-missing in CI to avoid unnecessary API calls.
  2. Drift Detection:

    • By default, laratext:scan --write retranslates drifted keys (source text changed in code).
    • Fix: Use --only-missing to skip drift or manually edit lang/{locale}.json.
  3. Placeholder Mismatches:

    • If placeholders (e.g., :name) are missing in translations, ensure the default value includes them:
      // Bad: Missing placeholder in default → translation may omit it.
      text('greeting', 'Hello!', ['name' => $user->name]);
      
      // Good: Include placeholder in default.
      text('greeting', 'Hello, :name!', ['name' => $user->name]);
      
  4. Orphaned Keys:

    • Keys in lang/ files but unused in code can bloat translations.
    • Solution: Run --prune periodically:
      php artisan laratext:scan --write --prune
      
  5. Auto-Generated Text Quirks:

    • Auto-generated text (e.g., text('user_profile') → "User Profile") may not match your intent.
    • Tip: Explicitly define keys for critical strings to avoid surprises.

Debugging

  • Check Scan Output: Run with --diff to preview changes:
    php artisan laratext:scan --dry --diff
    
  • Log Translations: Enable Laravel logging to debug API responses:
    \Log::debug('Translation response:', $translator->translate(...));
    
  • Validate Keys: Use php artisan laratext:scan without --write to list missing keys.

Extension Points

  1. Custom Translators:

    • Extend TranslatorInterface for proprietary services:
      php artisan make:translator DeepLTranslator
      
    • Implement translateMany() for batch efficiency.
  2. Pre-Translation Hooks:

    • Override the scan command to add validation:
      // app/Console/Commands/ScanTranslations.php
      protected function handle()
      {
          $keys = $this->collectKeys();
          $this->validateKeys($keys); // Custom logic
          parent::handle();
      }
      
  3. Post-Translation Processing:

    • Use Laravel events to modify translations (e.g., sanitize HTML):
      event(new TranslatedText($key, $translation));
      
    • Listen in an event service provider:
      public function boot()
      {
          TranslatedText::listen(function ($event) {
              $event->translation = strip_tags($event->translation);
          });
      }
      

Performance Tips

  • Batch Translations: Prefer translateMany() over single calls in custom translators.
  • Cache Results: Cache translations in Redis/Memcached for frequent keys:
    $translation = Cache::remember("text:{$key}:{$locale}", now()->addHours(1), function() use ($key, $locale) {
        return text($key);
    });
    
  • Limit Languages: Scan only needed languages with --lang=es,fr.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope