定制 jeromejhipolito/laravel-translation-middleware 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jeromejhipolito/laravel-translation-middleware

Composer 安装命令:

composer require jeromejhipolito/laravel-translation-middleware

包简介

Automatic locale detection middleware and translation traits for Laravel APIs. Detects Accept-Language header and provides HasTranslations trait for models.

README 文档

README

Automatic locale detection middleware and translation traits for Laravel APIs. Detects Accept-Language header and provides HasTranslations trait for models with JSON-stored translations.

Features

  • Automatically detects user's preferred language from Accept-Language header
  • Sets Laravel's app locale based on the detected language
  • Provides HasTranslations trait for models with JSON translation columns
  • Provides TranslatableResource trait for API resources
  • Supports locale fallbacks
  • Configurable supported locales
  • Excludes specific routes from locale detection

Requirements

  • PHP 8.2+
  • Laravel 11.0+ or 12.0+

Installation

composer require jeromejhipolito/laravel-translation-middleware

The package will auto-register its service provider.

Configuration

Publish the configuration file:

php artisan vendor:publish --tag=translation-config

This will create config/translation.php:

return [
    // HTTP header name for locale detection
    'header' => env('TRANSLATION_HEADER', 'Accept-Language'),

    // Default locale when no header is provided
    'default' => env('TRANSLATION_DEFAULT', 'en'),

    // Supported locales (empty array = accept all)
    'supported_locales' => ['en', 'ja', 'ko', 'zh', 'es', 'fr', 'de', 'pt', 'it', 'ru'],

    // Fallback when translation not available
    'fallback' => env('TRANSLATION_FALLBACK', 'en'),

    // Column suffix for translations (e.g., title_translations)
    'column_suffix' => '_translations',

    // Parse 'en-US' to 'en' (true) or keep full code (false)
    'parse_language_only' => true,

    // Routes to skip locale detection
    'excluded_routes' => [],
];

Usage

1. Register the Middleware

Add the middleware to your routes in bootstrap/app.php:

use JeromeJHipolito\TranslationMiddleware\Middleware\SetLocaleMiddleware;

->withMiddleware(function (Middleware $middleware) {
    $middleware->api(append: [
        SetLocaleMiddleware::class,
    ]);
})

2. Add HasTranslations Trait to Models

use Illuminate\Database\Eloquent\Model;
use JeromeJHipolito\TranslationMiddleware\Traits\HasTranslations;

class Article extends Model
{
    use HasTranslations;

    protected $fillable = [
        'title',
        'content',
        'title_translations',
        'content_translations',
    ];

    protected $casts = [
        'title_translations' => 'array',
        'content_translations' => 'array',
    ];

    // Define which attributes are translatable
    protected array $translatable = ['title', 'content'];
}

3. Database Migration

Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('title');                    // Default value
    $table->json('title_translations')->nullable();  // Translations
    $table->text('content');
    $table->json('content_translations')->nullable();
    $table->timestamps();
});

4. Store Translations

$article = Article::create([
    'title' => 'Hello World',
    'content' => 'This is the content.',
]);

// Set individual translations
$article->setTranslation('title', 'ja', 'こんにちは世界');
$article->setTranslation('title', 'ko', '안녕하세요 세계');
$article->save();

// Or set multiple at once
$article->setTranslations('title', [
    'ja' => 'こんにちは世界',
    'ko' => '안녕하세요 세계',
    'zh' => '你好世界',
]);
$article->save();

5. Retrieve Translations

// Uses current app locale (set by middleware)
$title = $article->getTranslation('title');

// Specify locale explicitly
$title = $article->getTranslation('title', 'ja');

// Get all translations
$translations = $article->getTranslations('title');
// ['ja' => 'こんにちは世界', 'ko' => '안녕하세요 세계']

// Check if translation exists
if ($article->hasTranslation('title', 'fr')) {
    // ...
}

// Get available locales
$locales = $article->getAvailableLocales('title');
// ['ja', 'ko', 'zh']

6. Use TranslatableResource in API Resources

use Illuminate\Http\Resources\Json\JsonResource;
use JeromeJHipolito\TranslationMiddleware\Traits\TranslatableResource;

class ArticleResource extends JsonResource
{
    use TranslatableResource;

    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->translated('title'),      // Auto-translated
            'content' => $this->translated('content'),  // Auto-translated
            'available_translations' => $this->availableTranslations('title'),
            'created_at' => $this->created_at,
        ];
    }
}

Client-Side Usage

Send the preferred language in the Accept-Language header:

fetch('/api/articles/1', {
    headers: {
        'Accept-Language': 'ja',
    },
});

// Response:
// {
//     "id": 1,
//     "title": "こんにちは世界",
//     "content": "これはコンテンツです",
//     "available_translations": ["ja", "ko", "zh"]
// }

API Reference

HasTranslations Trait Methods

Method Description
getTranslation($attribute, $locale = null) Get translated value
setTranslation($attribute, $locale, $value) Set translation for locale
setTranslations($attribute, $translations) Set multiple translations
getTranslations($attribute) Get all translations array
hasTranslation($attribute, $locale) Check if translation exists
removeTranslation($attribute, $locale) Remove translation
getAvailableLocales($attribute) Get available locale codes
getAllAvailableLocales() Get all locales across attributes
getTranslatableAttributes() Get list of translatable attributes
translated($locale = null) Get all translated attributes
toArrayTranslated($locale = null) Convert model to array with translations

TranslatableResource Trait Methods

Method Description
getLocale() Get current locale
translated($attribute) Get translated value
translatedWhen($condition, $attribute) Conditional translation
availableTranslations($attribute) Get available locales
allAvailableTranslations() Get all available locales
withTranslationMetadata() Get metadata array
mergeTranslationMetadataWhen($condition) Conditional metadata

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.

Credits

jeromejhipolito/laravel-translation-middleware 适用场景与选型建议

jeromejhipolito/laravel-translation-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「i18n」 「translation」 「api」 「locale」 「middleware」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jeromejhipolito/laravel-translation-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jeromejhipolito/laravel-translation-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 jeromejhipolito/laravel-translation-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 11
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-02-02