almoayad/laratrans
Composer 安装命令:
composer require almoayad/laratrans
包简介
LaraTrans is a Laravel package that simplifies the process of handling translations for your models. It allows you to easily create, update, and delete translations for specific model properties, making your application ready for multilingual support with minimal effort.
README 文档
README
LaraTrans
LaraTrans is a Laravel package that simplifies the process of handling translations for your models. It allows you to easily create, update, and delete translations for specific model properties, making your application ready for multilingual support with minimal effort.
Version 3.0 Updates
- Multiple Storage Strategies
- Single table mode (default)
- Dedicated tables mode for better organization and performance
- Migration System
- Easily switch between storage strategies
- Migrate existing translations between strategies
- Clean up unused translation tables
- Enhanced Validation
- Property-specific validation rules
- Required locales per property
- Unique translation validation
- Improved API
- Strategy-based architecture
- Better performance and reliability
- Extended translation methods
- Added support for Laravel 11
Requirements
- PHP 8.2 or higher
- Laravel 8.0 or higher (including Laravel 11)
Installation
You can install the package via Composer:
composer require almoayad/laratrans
Next, publish the migration and configuration files:
php artisan vendor:publish --provider="Almoayad\LaraTrans\LaraTransServiceProvider" --tag="migrations" php artisan vendor:publish --provider="Almoayad\LaraTrans\LaraTransServiceProvider" --tag="config"
Then, run the migration:
php artisan migrate
Configuration
After publishing the configuration file, you can customize various aspects of LaraTrans in config/laratrans.php:
return [ // Storage strategies 'storage' => [ 'mode' => 'single_table', // or 'dedicated_tables' 'table_prefix' => 'trans_', 'table_name' => 'laratrans_translations', ], // Caching 'cache' => [ 'enabled' => true, 'duration' => 3600, // 1 hour 'prefix' => 'laratrans_', ], // Locales 'locales' => [ 'default' => 'en', 'supported' => ['en', 'es', 'fr', 'ar'], 'fallback_locale' => 'en', 'auto_fallback' => true, ], // Models 'models' => [ 'translation' => \Almoayad\LaraTrans\Models\Translation::class, 'dedicated_translation' => \Almoayad\LaraTrans\Models\DedicatedTranslation::class, ], // Validation 'validation' => [ 'default_rules' => [ 'min' => 1, 'max' => 255, 'required_locales' => [], // Locales that must have translations ], 'properties' => [ // 'title' => [ // 'min' => 3, // 'max' => 100, // 'required_locales' => ['en', 'es'] // ], ], ], ];
Usage
Step 1: Add the HasTranslations Trait
Add the HasTranslations trait to your model:
use Almoayad\LaraTrans\Traits\HasTranslations; class SomeModel extends Model { use HasTranslations; }
Step 2: Create Translations
You can create translations in several ways:
// Method 1: Bulk creation via request $model = SomeModel::create($request->all()); // Automatically handles 'translations' array in request // Method 2: Bulk creation directly $model = SomeModel::create($request->except('translations')); $translations = [ ['locale' => 'ar', 'property_name' => 'name', 'value' => 'أسود'], ['locale' => 'en', 'property_name' => 'name', 'value' => 'black'], ['locale' => 'fr', 'property_name' => 'name', 'value' => 'noir'], ]; $model->updateModelTranslations($translations); // Method 3: Individual creation $model->setTranslation('name', 'black', 'en');
Step 3: Retrieve Translations
// Get translation for current locale $translation = $model->filterTranslation('name'); // Get translation for specific locale $translation = $model->filterTranslation('name', 'fr'); // Get all translations for current locale $translations = $model->localeTranslation()->get(); // Check if translation exists $exists = $model->checkTranslationExists('name', 'en');
Step 4: Query with Translations
// Query models with translations $models = SomeModel::withTranslation('name') ->whereTranslation('name', 'black') ->get();
Storage Strategies
Single Table Mode (default)
All translations are stored in one table with polymorphic relationships.
- Good for applications with fewer models needing translation
- Simple setup and migration
- Uses the standard
laratrans_translationstable
Dedicated Tables Mode
Each model has its own translation table for better performance and organization.
- Better for applications with many translatable models
- Improved query performance
- Better database organization
- Creates tables like
trans_products_translations,trans_categories_translations, etc.
Switching Storage Strategies
# Switch from single table to dedicated tables php artisan laratrans:migrate-strategy # Switch from dedicated tables to single table php artisan laratrans:migrate-strategy --reverse # Clean up old tables after migration (optional) php artisan laratrans:cleanup --single php artisan laratrans:cleanup --dedicated
Creating Dedicated Translation Tables
# Create a dedicated translation table for a model
php artisan laratrans:table Product
Validation
LaraTrans includes a robust validation system:
Global Validation Rules
'validation' => [ 'default_rules' => [ 'min' => 1, 'max' => 255, 'required_locales' => ['en'], // All translations must have English ], ],
Property-Specific Rules
'properties' => [ 'title' => [ 'min' => 3, 'max' => 100, 'required_locales' => ['en', 'es'] // Title must have English and Spanish ], 'description' => [ 'min' => 10, 'max' => 1000 ], ],
Validation in Practice
// Validation happens automatically try { $model->setTranslation('title', 'Too short', 'en'); } catch (ValidationException $e) { // Handle validation error } // Bulk translations are also validated $model->create([ 'translations' => [ ['locale' => 'en', 'property_name' => 'title', 'value' => 'Valid title'], ['locale' => 'es', 'property_name' => 'title', 'value' => 'Título válido'] ] ]);
Caching
LaraTrans includes a powerful caching system for improved performance. The TranslationCache trait provides automatic caching of translations with smart cache invalidation.
Setting Up Caching
- Add the TranslationCache trait to your model (after HasTranslations):
use Almoayad\LaraTrans\Traits\HasTranslations; use Almoayad\LaraTrans\Traits\TranslationCache; class Product extends Model { use HasTranslations, TranslationCache; }
- Configure caching options in
config/laratrans.php:
'cache' => [ 'enabled' => true, 'duration' => 3600, // Cache duration in seconds 'prefix' => 'laratrans_', // Cache key prefix ],
Using Cached Translations
// Get cached translation for current locale $translation = $model->getCachedTranslation('title'); // Get cached translation for specific locale $translation = $model->getCachedTranslation('title', 'es'); // Setting translations (automatically handles cache) $model->setTranslation('title', 'New Title', 'en');
Cache Invalidation
The cache is automatically invalidated in the following scenarios:
- When setting new translations via
setTranslation() - When deleting the model (all related translations are removed from cache)
- When the cache duration expires
- When bulk updating translations
Automatic Features
LaraTrans automatically:
- Validates translations based on your configuration
- Creates translations during model creation
- Updates translations during model updates
- Deletes translations when the model is deleted
- Falls back to the default locale when a translation is missing (configurable)
- Handles migrations between storage strategies
Customization
You can customize LaraTrans by:
- Extending the HasTranslations trait
- Modifying the configuration file
- Creating custom validation rules
- Adjusting the migration file
- Creating dedicated translation tables for specific models
Testing the Package Locally
- Add to your Laravel application's
composer.json:
"repositories": [ { "type": "path", "url": "../path/to/LaraTrans" } ],
- Then run:
composer require almoayad/laratrans
License
LaraTrans is open-source software licensed under the MIT license.
Feedback and Contributions
If you have any feedback or suggestions, feel free to open an issue or submit a pull request. Contributions are more than welcome!
Version History
- 3.0.0: Added storage strategies, migration system, enhanced validation, and Laravel 11 support
- 2.0.0: Added Laravel 11 support, validation system, and configuration options
- 1.0.4: Initial release with basic translation functionality
Developed with ❤️ by Mohamad Almoayad.
This package is maintained with pride by Mo Designs Studio.
almoayad/laratrans 适用场景与选型建议
almoayad/laratrans 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 71 次下载、GitHub Stars 达 7, 最近一次更新时间为 2024 年 08 月 28 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 almoayad/laratrans 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 almoayad/laratrans 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 71
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 8
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-08-28