PHPackages                             our-edu/laravel-translation-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. our-edu/laravel-translation-client

ActiveLibrary[API Development](/categories/api)

our-edu/laravel-translation-client
==================================

Laravel client package for consuming centralized translation service

1.2.0(1mo ago)0678[1 PRs](https://github.com/our-edu/laravel-translation-client/pulls)MITPHPPHP ^8.1|^8.2|^8.3

Since Dec 31Pushed 4mo agoCompare

[ Source](https://github.com/our-edu/laravel-translation-client)[ Packagist](https://packagist.org/packages/our-edu/laravel-translation-client)[ RSS](/packages/our-edu-laravel-translation-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (12)Versions (10)Used By (0)

Laravel Translation Client
==========================

[](#laravel-translation-client)

[![Latest Version](https://camo.githubusercontent.com/893b0b730d784d8f8095bf8e3358242d430ccc2bbb58ead351c360b5ef3f1ca8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f75722d6564752f6c61726176656c2d7472616e736c6174696f6e2d636c69656e742e737667)](https://packagist.org/packages/our-edu/laravel-translation-client)[![License](https://camo.githubusercontent.com/dd1d4d1422d4968c446fcd6a152e6bbf2b73a7535c635913050691e34ea8eccb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f75722d6564752f6c61726176656c2d7472616e736c6174696f6e2d636c69656e742e737667)](LICENSE)

A Laravel package for consuming centralized translation services. This package replaces Laravel's file-based translation loader with an API-based loader that fetches translations from a remote translation service.

Features
--------

[](#features)

- **API-based translations** - Fetch translations from a centralized service
- **Write translations** - Push translations back to the service
- **Multi-level caching** - Memory, Laravel cache, and service-side caching
- **Automatic updates** - Translations update without redeployment
- **Multi-tenant support** - Per-tenant translation isolation
- **Zero code changes** - Works with existing `trans()` and `__()` calls
- **High performance** - Sub-millisecond translation lookups
- **Graceful degradation** - Falls back to stale cache on API failures
- **Import from files** - Migrate existing Laravel translations

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x or 11.x

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require ouredu/laravel-translation-client
```

### 2. Publish Configuration

[](#2-publish-configuration)

```
php artisan vendor:publish --provider="OurEdu\TranslationClient\TranslationServiceProvider"
```

This will create `config/translation-client.php`.

### 3. Configure Environment

[](#3-configure-environment)

Add the following to your `.env` file:

```
TRANSLATION_SERVICE_URL=https://your-translation-service.com
TRANSLATION_PRELOAD=true
TRANSLATION_CLIENT=backend
```

### 4. Configure Available Locales

[](#4-configure-available-locales)

In `config/translation-client.php`, add:

```
'available_locales' => ['en', 'ar', 'fr'],
```

Configuration
-------------

[](#configuration)

All configuration options are in `config/translation-client.php`:

```
return [
    // Translation service base URL
    'service_url' => env('TRANSLATION_SERVICE_URL', 'http://localhost'),

    // Preload translations on boot (recommended for production)
    'preload' => env('TRANSLATION_PRELOAD', true),

    // Cache TTL in seconds
    'manifest_ttl' => env('TRANSLATION_MANIFEST_TTL', 300), // 5 minutes
    'bundle_ttl' => env('TRANSLATION_BUNDLE_TTL', 3600), // 1 hour

    // Client type: backend, frontend, mobile
    'client' => env('TRANSLATION_CLIENT', 'backend'),

    // HTTP timeout in seconds
    'http_timeout' => env('TRANSLATION_HTTP_TIMEOUT', 10),

    // Use stale cache on API failure
    'fallback_on_error' => env('TRANSLATION_FALLBACK_ON_ERROR', true),

    // Cache store (null = default)
    'cache_store' => env('TRANSLATION_CACHE_STORE'),

    // Logging
    'logging' => [
        'enabled' => env('TRANSLATION_LOGGING', false),
        'channel' => env('TRANSLATION_LOG_CHANNEL', 'stack'),
    ],

     /*
    |--------------------------------------------------------------------------
    | Available Locales
    |--------------------------------------------------------------------------
    |
    | The list of available locales to sync translations for
    |
    */
    'available_locales' => [
        'ar',
        'en',
    ],
];
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Once installed, use Laravel's translation functions as normal:

```
// In controllers
__('messages.welcome')
trans('validation.required')

// With replacements
trans('messages.hello', ['name' => 'Ahmed'])
```

### Commands

[](#commands)

#### Sync Translations

[](#sync-translations)

Manually fetch and cache translations:

```
# Sync all locales
php artisan translations:sync

# Sync specific locale
php artisan translations:sync --locale=ar

# Force refresh (clear cache first)
php artisan translations:sync --force
```

#### Clear Cache

[](#clear-cache)

Clear translation caches:

```
# Clear all translation caches
php artisan translations:clear-cache

# Clear specific locale
php artisan translations:clear-cache --locale=ar
```

#### Import Translations

[](#import-translations)

Import translations from Laravel lang files to the service:

```
# Import all locales
php artisan translations:import

# Import specific locale
php artisan translations:import --locale=ar

# Import from custom path
php artisan translations:import --path=/path/to/lang
```

### Scheduled Sync

[](#scheduled-sync)

Add to `app/Console/Kernel.php` to sync translations hourly:

```
protected function schedule(Schedule $schedule): void
{
    $schedule->command('translations:sync')->hourly();
}
```

### Middleware for Locale Detection

[](#middleware-for-locale-detection)

Add to `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'web' => [
        // ...
        \OurEdu\TranslationClient\Middleware\SetLocaleFromRequest::class,
    ],
];
```

This middleware detects locale from:

1. Query parameter (`?locale=ar`)
2. Header (`X-Locale: ar`)
3. Accept-Language header
4. Authenticated user preference

### Using the Facade

[](#using-the-facade)

#### Reading Translations

[](#reading-translations)

```
use OurEdu\TranslationClient\Facades\Translation;

// Check version
$manifest = Translation::checkVersion('ar');
// Returns: ['version' => 42, 'etag' => '...', 'updated_at' => '...']

// Fetch specific groups
$translations = Translation::fetchBundle('ar', ['messages', 'validation']);

// Load all translations
$all = Translation::loadTranslations('ar');

// Clear cache
Translation::clearCache('ar');
```

#### Writing Translations

[](#writing-translations)

```
// Push single translation
Translation::pushTranslation(
    locale: 'ar',
    group: 'messages',
    key: 'welcome',
    value: 'مرحبا'
);

// Push multiple translations
Translation::pushTranslations([
    [
        'locale' => 'ar',
        'group' => 'messages',
        'key' => 'hello',
        'value' => 'مرحباً',
        'client' => 'backend',
    ],
]);

// Import from Laravel lang files
Translation::importFromFiles('ar', lang_path());
```

### Programmatic Access

[](#programmatic-access)

```
use OurEdu\TranslationClient\Services\TranslationClient;

class MyService
{
    public function __construct(
        private TranslationClient $translationClient
    ) {}

    public function getTranslations()
    {
        return $this->translationClient->fetchBundle('ar', ['messages']);
    }
}
```

How It Works
------------

[](#how-it-works)

### Architecture

[](#architecture)

```
Laravel App → trans() → ApiTranslationLoader → TranslationClient → Translation Service API
                                ↓
                         Memory Cache (in-memory)
                                ↓
                         Laravel Cache (Redis/File)
                                ↓
                         Translation Service (Redis + DB)

```

### Caching Strategy

[](#caching-strategy)

1. **Memory Cache**: Loaded translations stored in PHP memory
2. **Laravel Cache**: Persistent cache with configurable TTL
3. **Version Checking**: Manifest API checked every 5 minutes
4. **Automatic Invalidation**: Cache refreshed when version changes

### Performance

[](#performance)

- **Cached Translation**: ~1-5ms (from memory)
- **Laravel Cache Hit**: ~5-10ms
- **API Call (first time)**: ~50-200ms
- **Manifest Check**: ~10-50ms

Multi-Tenant Support
--------------------

[](#multi-tenant-support)

For multi-tenant applications:

```
// Set tenant dynamically based on request
config(['translation-client.tenant_uuid' => $currentTenant->uuid]);

// Or extend the TranslationClient
class MultiTenantTranslationClient extends TranslationClient
{
    public function __construct()
    {
        parent::__construct();
        $this->tenantUuid = auth()->user()?->tenant_uuid;
    }
}
```

Error Handling
--------------

[](#error-handling)

The package handles errors gracefully:

- **API Unavailable**: Uses stale cache if available
- **Network Timeout**: Falls back to cached data
- **Invalid Response**: Logs error and returns empty array
- **Missing Translations**: Falls back to key name (Laravel default)

Enable logging for debugging:

```
TRANSLATION_LOGGING=true
TRANSLATION_LOG_CHANNEL=stack
```

Testing
-------

[](#testing)

When testing, you may want to disable API calls:

```
// In tests/TestCase.php
protected function setUp(): void
{
    parent::setUp();

    // Mock the translation client
    $this->mock(TranslationClient::class, function ($mock) {
        $mock->shouldReceive('loadTranslations')
            ->andReturn(['messages.welcome' => 'Welcome']);
    });
}
```

Troubleshooting
---------------

[](#troubleshooting)

### Translations not loading

[](#translations-not-loading)

1. Check service URL is correct: `php artisan config:cache`
2. Verify API is accessible: `curl https://your-service.com/translation/manifest?locale=en`
3. Enable logging: `TRANSLATION_LOGGING=true`
4. Check logs: `tail -f storage/logs/laravel.log`

### Cache not clearing

[](#cache-not-clearing)

```
php artisan cache:clear
php artisan translations:clear-cache
php artisan config:cache
```

### Performance issues

[](#performance-issues)

1. Ensure `TRANSLATION_PRELOAD=true` in production
2. Use Redis for caching instead of file cache
3. Increase cache TTL if translations rarely change

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Support
-------

[](#support)

For issues and questions, please use the [GitHub issue tracker](https://github.com/ouredu/laravel-translation-client/issues).

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance84

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 81.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~15 days

Recently: every ~22 days

Total

7

Last Release

44d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d85c4fda0cfea81414f36c09f5950ec1764db34e52e2162b6b16de73ca2f127a?d=identicon)[ouredu](/maintainers/ouredu)

---

Top Contributors

[![elwafa](https://avatars.githubusercontent.com/u/9096983?v=4)](https://github.com/elwafa "elwafa (13 commits)")[![ibnfarouk-ouredu](https://avatars.githubusercontent.com/u/225661343?v=4)](https://github.com/ibnfarouk-ouredu "ibnfarouk-ouredu (3 commits)")

---

Tags

apilaravellocalizationi18ntranslation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/our-edu-laravel-translation-client/health.svg)

```
[![Health](https://phpackages.com/badges/our-edu-laravel-translation-client/health.svg)](https://phpackages.com/packages/our-edu-laravel-translation-client)
```

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[resend/resend-laravel

Resend for Laravel

1191.4M6](/packages/resend-resend-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
