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"
    

    Configure .env with API keys (e.g., OPENAI_API_KEY) and config/texts.php with supported languages.

  2. First Use Case: Replace a hardcoded string in Blade:

    <!-- Before -->
    <h1>Welcome, {{ $user->name }}!</h1>
    
    <!-- After -->
    @text('welcome.user', 'Welcome, :name!', ['name' => $user->name])
    
  3. Auto-Generate Translations: Run the scan command to auto-translate missing keys:

    php artisan laratext:scan --write
    

Where to Look First

  • Blade Directives: Replace @lang or hardcoded strings with @text().
  • PHP Helpers: Use text('key', 'default_value') in controllers/services.
  • Configuration: Check config/texts.php for translator settings and supported languages.
  • Commands: Explore laratext:scan options for managing translations.

Implementation Patterns

Core Workflows

1. Translation Key Management

  • Naming Convention: Use dot notation for hierarchical keys (e.g., auth.login.title).
  • Auto-Generation: Leverage auto-generated text for quick prototyping:
    @text('user.profile.edit')  <!-- Auto-generates "Profile Edit" -->
    
  • Placeholders: Use :placeholder syntax for dynamic content:
    text('cart.summary', 'Total: $:amount', ['amount' => $total]);
    

2. Blade Integration

  • Directives: Prefer @text over @lang for consistency:
    @text('errors.validation.required', 'The :field is required.', ['field' => 'email'])
    
  • Fallbacks: Provide default values to avoid runtime errors:
    @text('settings.not_found', 'Settings not found', 'Fallback text')
    

3. PHP Integration

  • Controllers/Services:
    $message = text('notifications.email.subject', 'Your order #:order_id', ['order_id' => 12345]);
    
  • Validation Messages:
    $validator->errorBag('default')->messages()->put('email', text('errors.invalid_email'));
    

4. Translation Scanning

  • Daily Workflow:
    # After adding new keys
    php artisan laratext:scan --write
    
    # Before production
    php artisan laratext:scan --write --prune
    
  • Targeted Scans:
    # Translate only Spanish
    php artisan laratext:scan --write --lang=es
    
    # Use Claude for high-quality translations
    php artisan laratext:scan --write --translator=claude
    

5. Multi-Language Support

  • Language Switching:
    app()->setLocale('es'); // Switch to Spanish
    
  • Fallback Logic: Configure fallback locales in app/Providers/AppServiceProvider:
    LaravelLocalization::addLangs(['en', 'es', 'fr'], 'flags');
    LaravelLocalization::setFallbackLocales(['en', 'es']);
    

Integration Tips

  • Localization Middleware: Use eduLazaro\Laratext\Middleware\SetLocale to set locale from URL or session.
  • API Responses: Wrap API responses with translated keys:
    return response()->json(['message' => text('api.success')]);
    
  • Testing: Mock translators in tests:
    $this->app->bind(TranslatorInterface::class, function () {
        return new class implements TranslatorInterface {
            public function translate(string $text, string $from, array $to): array {
                return array_fill_keys($to, $text); // Mock: return same text
            }
        };
    });
    

Gotchas and Tips

Pitfalls

  1. Key Drift:

    • Issue: Changing source text (e.g., in Blade/PHP) breaks translations unless retranslated.
    • Fix: Use --resync to force a full retranslation or manually update lang/{locale}.json.
    • Warning: Drifted keys are logged but not retranslated by default (use --only-missing to skip).
  2. Placeholder Mismatches:

    • Issue: Placeholders (e.g., :name) must match exactly across languages. Typos in one language break replacements.
    • Fix: Validate placeholders in CI or use a regex pattern like /:\w+/.
  3. API Rate Limits:

    • Issue: Free tiers of OpenAI/Google may throttle requests during scans.
    • Fix:
      • Use --dry to preview changes before writing.
      • Implement retry logic in custom translators (see retries in config).
      • Batch requests with translateMany().
  4. Orphaned Keys:

    • Issue: Deleted @text calls leave stale keys in JSON files.
    • Fix: Run --prune periodically:
      php artisan laratext:scan --write --prune
      
  5. Auto-Generated Text:

    • Issue: Overly creative auto-generation (e.g., user_profile_edit → "User Profile Edit") may not match intent.
    • Fix: Explicitly define keys for critical strings or use --resync to override auto-generated values.

Debugging

  • Command Output: Use --diff to see changes before applying:
    php artisan laratext:scan --diff
    
  • Log Translations: Enable debug mode in config/texts.php:
    'debug' => env('APP_DEBUG', false),
    
  • Translator Errors: Check storage/logs/laravel.log for API failures (e.g., invalid API keys, timeouts).

Configuration Quirks

  1. Default Locale:

    • Ensure APP_LOCALE in .env matches the default locale in lang/{locale}.json.
    • Example: If APP_LOCALE=es, translations must exist in lang/es.json.
  2. Language Codes:

    • Use ISO 639-1 codes (e.g., en, es) for consistency with Laravel’s localization.
    • Avoid custom codes (e.g., en-US) unless explicitly supported by your translator.
  3. Translator Priorities:

    • The default_translator in config/texts.php applies globally. Override per-command with --translator.
    • Example: Use google for high-volume, low-cost translations:
      php artisan laratext:scan --write --translator=google
      

Extension Points

  1. Custom Translators:

    • Batch Optimization: Implement translateMany() to reduce API calls:
      public function translateMany(array $texts, string $from, array $to): array {
          // Use bulk API endpoints (e.g., Google Translate batch)
      }
      
    • Caching: Cache responses in Illuminate\Support\Facades\Cache:
      $cacheKey = "laratext:{$text}:{$from}:".implode(',', $to);
      return Cache::remember($cacheKey, now()->addHours(1), function () use ($text, $from, $to) {
          return $this->translate($text, $from, $to);
      });
      
  2. Key Sanitization:

    • Extend auto-generation logic by overriding the generateTextFromKey() method in a custom translator.
  3. Pre-Translation Hooks:

    • Use Laravel’s events to validate keys before translation:
      // In EventServiceProvider
      public function boot() {
          Event::listen('laratext.scanning', function ($keys) {
              // Validate keys against a regex or business rules
          });
      }
      
  4. Post-Translation Hooks:

    • Modify translations after generation (e.g., enforce brand guidelines):
      // In a service provider
      Event::listen('laratext.translated', function ($key, $translations) {
          foreach ($translations as $locale => &$text) {
              $text = str_replace('AI', 'Our Team', $text); // Branding fix
          }
      });
      

Performance Tips

  • Batch Processing: Prefer translateMany() over individual calls for large scans.
  • Concurrency: Run scans in CI/CD pipelines during off-peak hours to avoid rate limits.
  • Exclude Directories: Use --exclude to skip non-critical files (e.g., tests):
    php artisan laratext:scan --write --exclude="tests/"
    
  • Language Filtering: Translate only needed languages:
    php artisan laratext:scan --write --
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky