PHPackages                             aslnbxrz/simple-translation - 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. aslnbxrz/simple-translation

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

aslnbxrz/simple-translation
===========================

Lightweight file-first translations with DB backup for Laravel. Per-scope export and scanning.

2.0.1(7mo ago)198↓50%1MITPHPPHP ^8.1

Since Sep 18Pushed 7mo agoCompare

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

READMEChangelogDependencies (3)Versions (8)Used By (1)

Simple Translation
==================

[](#simple-translation)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d304ffc6d123a36c2e290840cd581c3eeabc37fe934f74015d94db7d608576f4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61736c6e6278727a2f73696d706c652d7472616e736c6174696f6e2e737667)](https://packagist.org/packages/aslnbxrz/simple-translation)[![Total Downloads](https://camo.githubusercontent.com/4bb5ab45d022e5c1eff710d15d79eb6922aa3b22c41b6d76159ab2b9c9db355c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f61736c6e6278727a2f73696d706c652d7472616e736c6174696f6e2e737667)](https://packagist.org/packages/aslnbxrz/simple-translation)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

*A lightweight, file-first translation manager for Laravel with database backup.*

Simple Translation uses a **file-first approach** with database backup. It lets you **scan** your codebase for translation keys, **import/export** them between database and files, and **organize** translations by scopes. It ships with a fast `___()` helper (like Laravel's `__()`), per-scope file storage (JSON or PHP), and handy Artisan commands (`scan`, `export`, `import`, `sync`) to keep your translations in sync.

---

🧭 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#-features)
- [Requirements](#-requirements)
- [Installation](#-installation)
- [Migrations](#-migrations)
- [Configuration](#-configuration)
- [Quick Start](#-quick-start)
- [Helper `___()`](#-helper-___)
- [Commands](#-commands)
    - [Scan](#scan)
    - [Export](#export)
    - [Sync](#sync)
- [Exporting to Files](#-exporting-to-files)
- [Caching (InMemory &amp; Redis)](#-caching-inmemory--redis)
- [Performance &amp; Scaling](#-performance--scaling)
- [Eloquent Models &amp; Schema](#-eloquent-models--schema)
- [Testing (Orchestra Testbench)](#-testing-orchestra-testbench)
- [Troubleshooting](#-troubleshooting)
- [FAQ](#-faq)
- [Versioning &amp; Compatibility](#-versioning--compatibility)
- [Security](#-security)
- [License](#-license)
- [Contributing](#-contributing)

---

✨ Features
----------

[](#-features)

- **File-First Strategy**: Prefers translations from per-scope files, with database as backup.
- **Scan &amp; Import/Export**: Parse `app/`, `resources/`, `*.blade.php`, `*.php`, `*.vue`, `*.js`, `*.ts` for translation calls and sync between files and database.
- **Per-Scope Organization**: Store translations in separate files per scope (e.g., `app.json`, `admin.json`).
- **Multiple File Formats**: Support for JSON (`{locale}/{scope}.json`) or PHP array (`{locale}/{scope}.php`) formats.
- **`___()` Helper**: File-first translation with automatic DB fallback and key creation.
- **Scopes Management**: Organize translations by scope (e.g., `app`, `admin`, `exceptions`).
- **In-Memory Caching**: Per-request memoization for blazing fast lookups.
- **Zero-config Autodiscovery**: Laravel auto-discovers the service provider.
- **Four Artisan Commands**: `scan`, `export`, `import`, and `sync`.

---

✅ Requirements
--------------

[](#-requirements)

- **PHP**: ^8.1
- **Laravel**: ^10.0|^11.0|^12.0
- **Database**: SQLite/MySQL/PostgreSQL (package-agnostic). SQLite is fine for testing.
- **Storage**: File system access for translation files.

---

📦 Installation
--------------

[](#-installation)

```
composer require aslnbxrz/simple-translation
```

Publish config:

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

Publish migrations:

```
# All migration files
php artisan vendor:publish --tag=simple-translation-migrations
```

Run migrations:

```
php artisan migrate
```

Publish seeder (optional):

```
php artisan vendor:publish --tag=simple-translation-seeders
```

---

⚙️ Configuration
----------------

[](#️-configuration)

`config/simple-translation.php`:

```
return [
    // Default scope used when none is provided.
    'default_scope' => 'app',

    // Scopes registry: used by --all and select options.
    'available_scopes' => [
        'app' => 'App',
        'admin' => 'Admin',
        'exceptions' => 'Exceptions',
    ],

    // Where to resolve available locales from: "config" or "database".
    'use_locales_from' => 'config',

    // Locales for "config" mode.
    'config_locales' => [
        ['code' => 'en', 'name' => 'English'],
    ],

    // Runtime store driver (also used by export). Per-scope files only.
    'translations' => [
        'driver' => 'json-per-scope', // json-per-scope | php-array-per-scope
        'drivers' => [
            // storage/lang/json/{locale}/{scope}.json
            'json-per-scope' => [
                'base_dir' => lang_path(),
                'pretty' => false, // pretty print json
                'lock' => true,  // LOCK_EX on write
            ],
            // lang/vendor/simple-translation/{locale}/{scope}.php
            'php-array-per-scope' => [
                'base_dir' => lang_path('vendor/simple-translation'),
                'lock' => true,  // LOCK_EX on write
            ],
        ],

        // Auto restore (import) on seeding:
        // If true, SimpleTranslationSeeder will import translations from files if DB is empty.
        'restore_on_seed' => true,

        // refill DB while importing:
        // true => app_texts va app_text_translations will be truncated
        // false => existing will be preserved, new will be added, missing will be removed (merge)
        'truncate_on_import' => false,
    ],
];
```

---

🚀 Quick Start
-------------

[](#-quick-start)

```
use Aslnbxrz\SimpleTranslation\Models\AppLanguage;
use Aslnbxrz\SimpleTranslation\Services\AppLanguageService;

// 1) Seed languages (if using database mode)
AppLanguage::updateOrCreate(['code' => 'en'], ['name' => 'English', 'is_active' => true]);
AppLanguage::updateOrCreate(['code' => 'ru'], ['name' => 'Русский', 'is_active' => true]);

// 2) Scan your codebase for translation keys
php artisan simple-translation:scan --scope=app

// 3) Export translations to files
php artisan simple-translation:export --scope=app

// 4) Use the helper in your views
echo ___('Welcome to our site'); // → Reads from files first, DB fallback
```

**File Structure:**

```
lang/
├── en/
│   ├── app.json          # App scope translations
│   └── admin.json        # Admin scope translations
└── ru/
    ├── app.json
    └── admin.json

```

### Seeder Support

[](#seeder-support)

The package includes a seeder that can automatically import existing translation files when the database is empty:

```
// In your DatabaseSeeder
$this->call(SimpleTranslationSeeder::class);
```

**Features:**

- Auto-imports translations from files when database is empty
- Configurable via `restore_on_seed` option
- Supports both JSON and PHP array formats

---

🧰 Helper `___()`
----------------

[](#-helper-___)

The `___()` helper uses a **file-first approach** with database fallback and automatic key creation.

```
{{ ___('Dashboard') }}               // default scope = app
{{ ___('Users', 'admin') }}          // custom scope
```

**How it works:**

1. **File Lookup**: Checks per-scope translation files first (fastest)
2. **Database Fallback**: If not found in files, checks database
3. **Auto-Creation**: If missing everywhere, creates DB key and stores key-as-value
4. **In-Memory Cache**: Caches results per request for optimal performance

---

🛠 Commands
----------

[](#-commands)

### Scan

[](#scan)

Extract translation keys from source files and persist them to database:

```
php artisan simple-translation:scan --paths=app,resources --scope=app
```

**Options:**

- `--paths` - CSV directories to scan (default: `app,resources`)
- `--ext` - CSV extensions to include (`php,blade.php,vue,js,ts`)
- `--scope` - Assign scope for found keys
- `--exclude` - CSV directories to skip (default: `vendor,node_modules,storage`)
- `--dry` - Dry-run mode (no database writes)
- `--no-progress` - Hide progress bar

### Export

[](#export)

Export database translations to per-scope files:

```
php artisan simple-translation:export --scope=app
php artisan simple-translation:export --all  # Export all configured scopes
```

**Options:**

- `--scope` - CSV scopes to export (e.g., `app,admin`)
- `--all` - Export all scopes from config
- `--locales` - CSV locales filter (e.g., `en,ru`)

### Import

[](#import)

Import per-scope files into database:

```
php artisan simple-translation:import --scope=app
php artisan simple-translation:import --all --truncate  # Truncate before import
```

**Options:**

- `--scope` - CSV scopes to import
- `--all` - Import all configured scopes
- `--locales` - CSV locales filter
- `--truncate` - Force truncate before import

### Sync

[](#sync)

Run **scan + export** in one step:

```
php artisan simple-translation:sync --scope=app
```

**Options:**

- `--paths`, `--ext`, `--exclude` - Scan options
- `--scope`, `--all`, `--locales` - Export options
- `--dry` - Only scan (no database writes, no export)
- `--no-progress` - Hide progress bar

**When to use `sync`:**

- **Deploy pipelines**: Update database keys and regenerate files in one command
- **Initial setup**: Populate database from code and immediately export
- **Development workflow**: Keep files and database in sync

---

📤 File Storage &amp; Formats
----------------------------

[](#-file-storage--formats)

Translations are stored in per-scope files with configurable formats:

### JSON Format (Default)

[](#json-format-default)

```
lang/
├── en/
│   ├── app.json          # {"Welcome": "Welcome", "Dashboard": "Dashboard"}
│   └── admin.json        # {"Users": "Users", "Settings": "Settings"}
└── ru/
    ├── app.json          # {"Welcome": "Добро пожаловать", "Dashboard": "Панель"}
    └── admin.json

```

### PHP Array Format

[](#php-array-format)

```
lang/vendor/simple-translation/
├── en/
│   ├── app.php           #
