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.
Installation
composer require weglot/weglot-php
Add the service provider to config/app.php:
'providers' => [
// ...
Weglot\Weglot\WeglotServiceProvider::class,
],
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
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);
}
Translation Management
$translations = Weglot::getTranslations();
Weglot::updateTranslation($sourceText, $targetLanguage, $translatedText);
Weglot::updateTranslations([
['source' => 'Hello', 'target' => 'es', 'translation' => 'Hola'],
['source' => 'World', 'target' => 'fr', 'translation' => 'Monde'],
]);
Language Handling
$languages = Weglot::getLanguages();
Weglot::setDefaultLanguage('en');
Project Configuration
$project = Weglot::getProject();
Weglot::updateProject(['name' => 'New Project Name']);
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();
});
API Rate Limits
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();
}
Authentication Errors
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
}
Language Code Mismatches
es for Spanish). Double-check codes when updating translations.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(),
]);
}),
]));
});
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;
});
}
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);
});
});
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
}
How can I help you explore Laravel packages today?