Weave 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

Weglot Php Laravel Package

weglot/weglot-php

PHP client library for the Weglot Translation API. Detects source language, translates text, manages languages and settings, and helps integrate Weglot into PHP apps and services with simple, typed requests and responses.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require weglot/weglot-php
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Weglot\Weglot\WeglotServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Weglot\Weglot\WeglotServiceProvider"
    

    Update .env with your Weglot API credentials:

    WEGLOT_API_KEY=your_api_key_here
    WEGLOT_API_SECRET=your_api_secret_here
    
  3. First Use Case: Fetching Translations Inject the Weglot client into a controller or service:

    use Weglot\Weglot\Facades\Weglot;
    
    public function getTranslations()
    {
        $translations = Weglot::getTranslations();
        return response()->json($translations);
    }
    

Implementation Patterns

Core Workflows

  1. Translation Management

    • Fetching Translations:
      $translations = Weglot::getTranslations();
      
    • Updating Translations:
      Weglot::updateTranslation($sourceText, $targetLanguage, $translatedText);
      
    • Bulk Operations:
      Weglot::updateTranslations([
          ['source' => 'Hello', 'target' => 'es', 'translation' => 'Hola'],
          ['source' => 'World', 'target' => 'fr', 'translation' => 'Monde'],
      ]);
      
  2. Language Handling

    • List available languages:
      $languages = Weglot::getLanguages();
      
    • Set default language:
      Weglot::setDefaultLanguage('en');
      
  3. Project Configuration

    • Fetch project details:
      $project = Weglot::getProject();
      
    • Update project settings:
      Weglot::updateProject(['name' => 'New Project Name']);
      

Integration Tips

  • Middleware for API Key Protection Use middleware to validate API keys before allowing Weglot operations:

    public function handle($request, Closure $next)
    {
        if (!config('weglot.api_key')) {
            abort(403, 'Weglot API key not configured.');
        }
        return $next($request);
    }
    
  • Event-Driven Updates Trigger Weglot updates on model events (e.g., saved):

    public function saved(Article $article)
    {
        if ($article->isDirty('title')) {
            Weglot::updateTranslation(
                $article->getOriginal('title'),
                'es',
                $article->title
            );
        }
    }
    
  • Caching Responses Cache translation responses to reduce API calls:

    $translations = Cache::remember('weglot.translations', now()->addHours(1), function () {
        return Weglot::getTranslations();
    });
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • Weglot’s API has rate limits. Handle Weglot\Weglot\Exceptions\RateLimitExceededException gracefully:
      try {
          $translations = Weglot::getTranslations();
      } catch (\Weglot\Weglot\Exceptions\RateLimitExceededException $e) {
          Log::warning('Weglot API rate limit exceeded. Retrying in 60 seconds...');
          sleep(60);
          retry();
      }
      
  2. Authentication Errors

    • Ensure WEGLOT_API_KEY and WEGLOT_API_SECRET are correctly set in .env. Test with:
      try {
          Weglot::getProject();
      } catch (\Weglot\Weglot\Exceptions\AuthenticationException $e) {
          // Handle invalid credentials
      }
      
  3. Language Code Mismatches

    • Weglot uses ISO 639-1 language codes (e.g., es for Spanish). Double-check codes when updating translations.

Debugging

  • Enable Debug Mode Set debug to true in config/weglot.php to log API requests/responses:

    'debug' => env('WEGLOT_DEBUG', false),
    
  • Log API Responses Extend the client to log raw responses:

    Weglot::extend(function ($client) {
        $client->getClient()->getHandler()->setHandler(new \GuzzleHttp\HandlerStack([
            new \GuzzleHttp\Middleware::tap(function ($request, $options, $next) {
                Log::debug('Weglot API Request:', [
                    'url' => (string) $request->getUri(),
                    'method' => $request->getMethod(),
                    'headers' => $request->getHeaders(),
                ]);
            }),
        ]));
    });
    

Extension Points

  1. Custom HTTP Client Override the default Guzzle client in the service provider:

    public function register()
    {
        $this->app->singleton(WeglotClient::class, function ($app) {
            $client = new WeglotClient(
                config('weglot.api_key'),
                config('weglot.api_secret')
            );
            $client->setHttpClient(new CustomHttpClient());
            return $client;
        });
    }
    
  2. Translation Pre/Post-Processing Hook into translation updates:

    Weglot::extend(function ($client) {
        $client->on('updating-translation', function ($source, $target, $translation) {
            // Sanitize or modify translation before sending
            return strtoupper($translation);
        });
    });
    
  3. Webhook Integration Use Weglot’s webhooks to sync translations in real-time. Store the webhook secret in config/weglot.php and validate incoming requests:

    public function handleWebhook(Request $request)
    {
        $payload = $request->getContent();
        $signature = $request->header('X-Weglot-Signature');
    
        if (!hash_equals(
            hash_hmac('sha256', $payload, config('weglot.webhook_secret')),
            $signature
        )) {
            abort(403);
        }
    
        // Process webhook payload
    }
    
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.
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route