PHPackages                             almoayad/laratrans - 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. [Localization &amp; i18n](/categories/localization)
4. /
5. almoayad/laratrans

ActiveLibrary[Localization &amp; i18n](/categories/localization)

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.

3.0.0(1y ago)8711MITPHPPHP ^8.2

Since Aug 28Pushed 1y ago1 watchersCompare

[ Source](https://github.com/mohamadalmoayad/LaraTrans)[ Packagist](https://packagist.org/packages/almoayad/laratrans)[ RSS](/packages/almoayad-laratrans/feed)WikiDiscussions main Synced today

READMEChangelog (8)Dependencies (1)Versions (13)Used By (0)

[![Mo Designs Studio Logo](https://camo.githubusercontent.com/4b86dfd398d1dcf55a063c763fb33311529fa5ba9cf0a3d5e27ee8fed32b7c70/68747470733a2f2f7777772e6d6f64657369676e7373747564696f2e636f6d2f5f6e6578742f696d6167653f75726c3d253246696d616765732532466c6f676f2532466d6f2d64657369676e732d6c6f676f2e67696626773d32353626713d3735)](https://www.modesignsstudio.com)

LaraTrans
=========

[](#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
-------------------

[](#version-30-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
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 8.0 or higher (including Laravel 11)

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

[](#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
-------------

[](#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
-----

[](#usage)

### Step 1: Add the HasTranslations Trait

[](#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

[](#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

[](#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

[](#step-4-query-with-translations)

```
// Query models with translations
$models = SomeModel::withTranslation('name')
    ->whereTranslation('name', 'black')
    ->get();
```

Storage Strategies
------------------

[](#storage-strategies)

### Single Table Mode (default)

[](#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_translations` table

### Dedicated Tables Mode

[](#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

[](#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

[](#creating-dedicated-translation-tables)

```
# Create a dedicated translation table for a model
php artisan laratrans:table Product
```

Validation
----------

[](#validation)

LaraTrans includes a robust validation system:

### Global Validation Rules

[](#global-validation-rules)

```
'validation' => [
    'default_rules' => [
        'min' => 1,
        'max' => 255,
        'required_locales' => ['en'], // All translations must have English
    ],
],
```

### Property-Specific Rules

[](#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-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
-------

[](#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

[](#setting-up-caching)

1. 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;
}
```

2. Configure caching options in `config/laratrans.php`:

```
'cache' => [
    'enabled' => true,
    'duration' => 3600, // Cache duration in seconds
    'prefix' => 'laratrans_', // Cache key prefix
],
```

### Using Cached Translations

[](#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

[](#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
------------------

[](#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
-------------

[](#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
---------------------------

[](#testing-the-package-locally)

1. Add to your Laravel application's `composer.json`:

```
"repositories": [
    {
        "type": "path",
        "url": "../path/to/LaraTrans"
    }
],
```

2. Then run:

```
composer require almoayad/laratrans
```

License
-------

[](#license)

LaraTrans is open-source software licensed under the MIT license.

Feedback and Contributions
--------------------------

[](#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
---------------

[](#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.
--------------------------------------

[](#developed-with-️-by-mohamad-almoayad)

---

This package is maintained with pride by [Mo Designs Studio](https://www.modesignsstudio.com).

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance43

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~21 days

Recently: every ~37 days

Total

11

Last Release

456d ago

Major Versions

1.0.4 → v2.x-dev2024-11-01

2.1.3 → v3.x-dev2025-04-02

PHP version history (2 changes)1.0.1PHP ^7.4 || ^8.0

v2.x-devPHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/64a82f833e15a654305354b4e41da7d8b04ef635de051c0815db3d4c77c4edbe?d=identicon)[mohamad almoayad](/maintainers/mohamad%20almoayad)

---

Top Contributors

[![mohamadalmoayad](https://avatars.githubusercontent.com/u/23522170?v=4)](https://github.com/mohamadalmoayad "mohamadalmoayad (51 commits)")

### Embed Badge

![Health badge](/badges/almoayad-laratrans/health.svg)

```
[![Health](https://phpackages.com/badges/almoayad-laratrans/health.svg)](https://phpackages.com/packages/almoayad-laratrans)
```

###  Alternatives

[illuminate/translation

The Illuminate Translation package.

6938.0M568](/packages/illuminate-translation)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[bezhansalleh/filament-language-switch

Zero config Language Switch(Changer/Localizer) plugin for filamentphp admin

3581.3M27](/packages/bezhansalleh-filament-language-switch)[erag/laravel-lang-sync-inertia

A powerful Laravel package for syncing and managing language translations across backend and Inertia.js (Vue/React/Svelte) frontends, offering effortless localization, auto-sync features, and smooth multi-language support for modern Laravel applications.

4925.3k](/packages/erag-laravel-lang-sync-inertia)

PHPackages © 2026

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