PHPackages                             tonydev/lara-glot - 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. tonydev/lara-glot

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

tonydev/lara-glot
=================

Smart Auto-Translation for Laravel Models with JSON/HTML support

v1.1.3(1w ago)08↓91.7%MITPHPPHP ^8.3

Since Apr 5Pushed 1mo agoCompare

[ Source](https://github.com/t27124949-cell/lara-glot)[ Packagist](https://packagist.org/packages/tonydev/lara-glot)[ RSS](/packages/tonydev-lara-glot/feed)WikiDiscussions main Synced 3d ago

READMEChangelogDependencies (18)Versions (7)Used By (0)

LaraGlot 🌍
==========

[](#laraglot-)

**Smart Auto-Translation for Laravel Models, Language Files &amp; Nested Content**

LaraGlot is an industrial-strength translation pipeline for Laravel applications. It intelligently translates:

- Eloquent models
- Nested JSON structures
- Filament Page Builder sections
- Static PHP language files
- SEO metadata
- Rich HTML content

…while protecting placeholders, HTML, IDs, slugs, application logic, and structural data from being corrupted by translation engines or LLMs.

Built for modern Laravel applications, LaraGlot combines:

- Queue-based background processing
- Smart recursive traversal
- Multi-layer caching
- AI-powered translation drivers
- Filament admin tooling
- Retry &amp; timeout protection
- Batch translation optimization

---

Table of Contents
=================

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Driver Architecture](#driver-architecture)
- [Model Setup](#model-setup)
- [Language File Translation](#language-file-translation)
- [Queue Setup &amp; Timeouts](#queue-setup--timeouts)
- [Artisan Commands](#artisan-commands)
- [Filament Integration](#filament-integration)
- [Caching Strategy](#caching-strategy)
- [Architecture](#architecture)
- [Service Responsibilities](#service-responsibilities)
- [Logging &amp; Monitoring](#logging--monitoring)
- [Failure Recovery](#failure-recovery)
- [Performance Optimizations](#performance-optimizations)
- [License](#license)

---

Requirements
============

[](#requirements)

RequirementVersionPHP`^8.1`Laravel`^10.0 | ^11.0`Filament`^3.0`spatie/laravel-translatable`^6.0`---

Installation
============

[](#installation)

```
composer require tonydev/lara-glot
```

---

Publish the Config
------------------

[](#publish-the-config)

```
php artisan vendor:publish --tag=lara-glot-config
```

---

Register the Commands
---------------------

[](#register-the-commands)

### Laravel 10

[](#laravel-10)

Register commands inside `app/Console/Kernel.php`:

```
protected $commands = [
    \Tonydev\LaraGlot\Commands\TranslateFilesCommand::class,
    \Tonydev\LaraGlot\Commands\DispatchTranslations::class,
];
```

---

### Laravel 11

[](#laravel-11)

Register commands inside `bootstrap/app.php`:

```
->withCommands([
    \Tonydev\LaraGlot\Commands\TranslateFilesCommand::class,
    \Tonydev\LaraGlot\Commands\DispatchTranslations::class,
])
```

---

Configuration
=============

[](#configuration)

After publishing, open:

```
config/lara-glot.php
```

Example configuration:

```
return [

    /*
    |--------------------------------------------------------------------------
    | Source Locale
    |--------------------------------------------------------------------------
    */
    'source_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Translation Driver
    |--------------------------------------------------------------------------
    | Supported:
    | - openai
    | - google
    | - deepl
    | - ollama
    */
    'translator' => env('LARAGLOT_DRIVER', 'openai'),

    /*
    |--------------------------------------------------------------------------
    | Registered Models
    |--------------------------------------------------------------------------
    */
    'models' => [
        \App\Models\Page::class,
        \App\Models\Post::class,
    ],

    /*
    |--------------------------------------------------------------------------
    | Target Languages
    |--------------------------------------------------------------------------
    */
    'languages' => [
        'es' => ['name' => 'Español',   'flag' => '🇪🇸'],
        'fr' => ['name' => 'Français',  'flag' => '🇫🇷'],
        'de' => ['name' => 'Deutsch',   'flag' => '🇩🇪'],
        'ak' => ['name' => 'Twi',       'flag' => '🇬🇭'],
        'pt' => ['name' => 'Português', 'flag' => '🇧🇷'],
        'ar' => ['name' => 'العربية',   'flag' => '🇸🇦'],
    ],

    /*
    |--------------------------------------------------------------------------
    | Ignored Structural Keys
    |--------------------------------------------------------------------------
    | Keys that should NEVER be translated.
    */
    'ignored_keys' => [
        'id',
        'uuid',
        'slug',
        'url',
        'image',
        'icon',
        'sort_order',
        'layout_type',
        'created_at',
        'updated_at',
        'color',
        'is_active',
    ],

    /*
    |--------------------------------------------------------------------------
    | Excluded Language Files
    |--------------------------------------------------------------------------
    */
    'exclude_files' => [
        'auth',
        'pagination',
        'passwords',
        'validation',
    ],

    /*
    |--------------------------------------------------------------------------
    | Queue Name
    |--------------------------------------------------------------------------
    */
    'queue' => 'translations',

    /*
    |--------------------------------------------------------------------------
    | Cache Expiry
    |--------------------------------------------------------------------------
    | Default: 30 days
    */
    'cache_expiry' => 2592000,

];
```

---

Driver Architecture
===================

[](#driver-architecture)

LaraGlot is driver-agnostic and supports both traditional translation engines and modern AI/LLM providers.

---

Supported Drivers
-----------------

[](#supported-drivers)

DriverPurpose`openai`AI-powered contextual translations`google`Fast traditional translations`deepl`High-quality professional translations`ollama`Local/self-hosted LLM translation---

OpenAI Driver (Recommended)
---------------------------

[](#openai-driver-recommended)

The OpenAI driver is optimized for large-scale translation workloads.

### Features

[](#features)

- JSON-mode batch translation
- Chunked translation pipelines
- Concurrent processing
- Retry handling
- API timeout protection
- Structured response validation

### Batch Optimization

[](#batch-optimization)

Instead of translating one string at a time:

```
[
    "title" => "Welcome",
    "button" => "Read More",
    "footer" => "Contact Us",
]
```

LaraGlot sends grouped translation chunks to dramatically reduce:

- API requests
- latency
- token usage
- overall cost

---

Google / DeepL Drivers
----------------------

[](#google--deepl-drivers)

Traditional translation APIs optimized for:

- speed
- consistency
- lower latency
- deterministic outputs

Ideal for applications needing high-volume static translations.

---

Ollama Driver
-------------

[](#ollama-driver)

Run translations entirely locally using self-hosted LLMs.

Perfect for:

- private deployments
- air-gapped systems
- sensitive data
- cost reduction

---

Model Setup
===========

[](#model-setup)

LaraGlot works alongside `spatie/laravel-translatable`.

---

1. Add the Traits
-----------------

[](#1-add-the-traits)

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Tonydev\LaraGlot\Traits\HasSmartTranslations;

class Page extends Model
{
    use HasTranslations, HasSmartTranslations;

    public array $translatable = [
        'title',
        'content',
        'meta_title',
        'meta_description',
    ];

    public function getTranslatableAttributes(): array
    {
        return $this->translatable;
    }
}
```

---

2. Page Builder &amp; Recursive Translation
-------------------------------------------

[](#2-page-builder--recursive-translation)

LaraGlot automatically detects nested structures and recursively traverses them.

Example:

```
class Page extends Model
{
    use HasTranslations, HasSmartTranslations;

    public function sections(): HasMany
    {
        return $this->hasMany(PageSection::class)
            ->orderBy('sort_order');
    }
}
```

---

What Gets Translated?
---------------------

[](#what-gets-translated)

LaraGlot intelligently translates:

✅ Nested arrays ✅ JSON blocks ✅ Builder content ✅ Rich text HTML ✅ `{ "en": "..." }` language maps ✅ Repeater blocks ✅ Filament Builder sections

---

What Gets Ignored?
------------------

[](#what-gets-ignored)

Structural/system keys are automatically skipped:

```
[
    'id',
    'slug',
    'url',
    'image',
    'layout_type',
    'sort_order',
]
```

This prevents corruption of application logic and relationships.

---

3. SEO Auto-Population
----------------------

[](#3-seo-auto-population)

If a model contains a `title` but empty SEO fields:

```
meta_title
meta_description
```

LaraGlot automatically pre-fills them from the English title before translation.

This guarantees multilingual SEO completeness even when editors forget metadata.

---

Language File Translation
=========================

[](#language-file-translation)

LaraGlot translates:

```
lang/en/*.php
```

into every configured locale.

---

Placeholder Protection
----------------------

[](#placeholder-protection)

Laravel placeholders are protected before sending content to the translator.

### Input

[](#input)

```
'hello' => 'Hello :name'
```

### Protected API Payload

[](#protected-api-payload)

```
Hello :name
```

### Final Output

[](#final-output)

```
'hello' => 'Bonjour :name'
```

This prevents engines from corrupting placeholders into invalid variants.

---

Pluralization Support
---------------------

[](#pluralization-support)

Pipe-delimited plural strings are translated segment-by-segment.

### Input

[](#input-1)

```
'items' => '{0} No items|[1,19] :count items|[20,*] :count items (bulk)'
```

### Output

[](#output)

```
'items' => '{0} Aucun article|[1,19] :count articles|[20,*] :count articles (en vrac)'
```

---

PHP Array Preservation
----------------------

[](#php-array-preservation)

Files are:

- flattened via `Arr::dot`
- translated safely
- rebuilt recursively
- saved using short-array syntax

Output is written to:

```
lang/{locale}/{file}.php
```

Directories are created automatically if missing.

---

Queue Setup &amp; Timeouts
==========================

[](#queue-setup--timeouts)

LaraGlot dispatches heavy translation work onto Laravel queues.

This keeps:

- web requests fast
- Filament responsive
- admin actions non-blocking

---

Start a Queue Worker
--------------------

[](#start-a-queue-worker)

```
php artisan queue:work --queue=translations,default
```

Recommended production command:

```
php artisan queue:work \
    --queue=translations,default \
    --timeout=620 \
    --tries=3
```

---

Cascading Timeout Strategy
==========================

[](#cascading-timeout-strategy)

Because AI providers can be slow, LaraGlot uses layered timeout protection.

LayerSettingDefaultQueue Job`$timeout``600s`Concurrent Worker`Concurrency::timeout()``300s`HTTP Request`Http::timeout()``120s`This prevents:

- hanging workers
- zombie jobs
- stalled queue pipelines

---

Supervisor Configuration
------------------------

[](#supervisor-configuration)

```
[program:laraglot-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/artisan queue:work redis --queue=translations,default --timeout=620 --tries=3
autostart=true
autorestart=true
numprocs=2
redirect_stderr=true
stdout_logfile=/var/log/supervisor/laraglot-worker.log
```

---

Job Retry Behaviour
-------------------

[](#job-retry-behaviour)

SettingValue`$tries``3``backoff()``[30, 60, 120]`Model Timeout`600s`File Timeout`300s`If providers rate-limit requests, LaraGlot retries automatically with progressive delays.

---

Artisan Commands
================

[](#artisan-commands)

`laraglot:sync`
===============

[](#laraglotsync)

Translate database models.

---

Process All Models
------------------

[](#process-all-models)

```
php artisan laraglot:sync
```

---

Process One Model
-----------------

[](#process-one-model)

```
php artisan laraglot:sync "App\Models\Page"
```

---

Force Re-Translation
--------------------

[](#force-re-translation)

```
php artisan laraglot:sync --force
```

---

Force Specific Model
--------------------

[](#force-specific-model)

```
php artisan laraglot:sync "App\Models\Post" --force
```

---

Internal Optimizations
----------------------

[](#internal-optimizations)

The sync command uses:

```
chunkById(100)
```

to safely process very large tables without memory exhaustion.

---

`laraglot:files`
================

[](#laraglotfiles)

Translate PHP language files.

---

Translate Everything
--------------------

[](#translate-everything)

```
php artisan laraglot:files
```

---

Single File
-----------

[](#single-file)

```
php artisan laraglot:files messages
```

---

Single Locale
-------------

[](#single-locale)

```
php artisan laraglot:files --locale=fr
```

---

Force Overwrite
---------------

[](#force-overwrite)

```
php artisan laraglot:files --force
```

---

Run Synchronously
-----------------

[](#run-synchronously)

Useful for CI pipelines:

```
php artisan laraglot:files --sync
```

---

Combined Example
----------------

[](#combined-example)

```
php artisan laraglot:files messages --locale=es --force --sync
```

---

Filament Integration
====================

[](#filament-integration)

LaraGlot ships with a full Filament admin interface.

Default route:

```
/admin/lara-glot-manager
```

---

LaraGlot Manager Features
=========================

[](#laraglot-manager-features)

1. Multi-File Selection
-----------------------

[](#1-multi-file-selection)

Choose one or many language files simultaneously.

---

2. AI Translation Preview
-------------------------

[](#2-ai-translation-preview)

Synchronously translate a file and preview the output before saving.

Features:

- side-by-side diff table
- editable translations
- manual correction support
- save reviewed output

---

3. Queue Dispatching
--------------------

[](#3-queue-dispatching)

Bulk-send translations to the background queue without waiting.

Perfect for:

- production deployments
- large multilingual sites
- mass content updates

---

4. Force Overwrite Toggle
-------------------------

[](#4-force-overwrite-toggle)

Control whether existing translations should be replaced.

---

5. Sync All Files
-----------------

[](#5-sync-all-files)

Header action that dispatches:

```
every file × every locale

```

combination automatically.

---

6. Force Re-Translate All
-------------------------

[](#6-force-re-translate-all)

Rebuild your entire translation set from scratch.

Useful when:

- changing AI providers
- improving prompts
- updating source English content

---

Resource Table Actions
======================

[](#resource-table-actions)

Add translation buttons directly to your Filament resources.

```
use Filament\Tables;
use Tonydev\LaraGlot\Jobs\TranslateModelJob;

public static function table(Table $table): Table
{
    return $table
        ->actions([
            Tables\Actions\Action::make('translate')
                ->label('Translate')
                ->icon('heroicon-m-language')
                ->color('warning')
                ->requiresConfirmation()
                ->action(fn ($record) => TranslateModelJob::dispatch(
                    get_class($record),
                    $record->getKey(),
                    true
                )->onQueue(config('lara-glot.queue'))),
        ])
        ->bulkActions([
            Tables\Actions\BulkAction::make('translate_selected')
                ->label('Translate Selected')
                ->icon('heroicon-m-language')
                ->requiresConfirmation()
                ->action(fn ($records) => $records->each(
                    fn ($record) => TranslateModelJob::dispatch(
                        get_class($record),
                        $record->getKey(),
                        true
                    )->onQueue(config('lara-glot.queue'))
                )),
        ]);
}
```

---

Caching Strategy
================

[](#caching-strategy)

LaraGlot uses a two-layer cache architecture to minimize API usage.

---

Layer 1 — RAM Cache
-------------------

[](#layer-1--ram-cache)

Per-request in-memory storage:

```
$localCache
```

If the same string appears multiple times during one translation job, LaraGlot instantly reuses the result.

---

Layer 2 — Persistent Cache
--------------------------

[](#layer-2--persistent-cache)

Stored using Laravel's cache driver:

- Redis
- File
- Memcached
- Database

Cache key format:

```
lara-glot.translation.{hash}

```

Where `{hash}` is:

```
md5(locale + source_string)
```

---

Cache Expiry
------------

[](#cache-expiry)

Default:

```
2592000 // 30 days
```

Configurable via:

```
cache_expiry
```

---

Force Cache Busting
-------------------

[](#force-cache-busting)

Passing:

```
--force
```

or enabling Force Overwrite:

- clears cached entries
- forces fresh API translations

---

Architecture
============

[](#architecture)

```
LaraGlot
├── Commands
│   ├── TranslateFilesCommand
│   └── DispatchTranslations
│
├── Jobs
│   ├── TranslateFilesJob
│   └── TranslateModelJob
│
├── Drivers
│   ├── OpenAiDriver
│   ├── GoogleDriver
│   ├── DeepLDriver
│   ├── OllamaDriver
│   └── AbstractDriver
│
├── Services
│   ├── TranslationService
│   ├── FileTranslationService
│   └── SmartTranslationService
│
├── Traits
│   └── HasSmartTranslations
│
└── Filament
    └── Pages
        └── LaraGlotManager

```

---

Service Responsibilities
========================

[](#service-responsibilities)

`TranslationService`
--------------------

[](#translationservice)

Core translation engine.

Responsibilities:

- API communication
- caching
- batching
- retries
- chunking
- timeout handling
- force refresh logic

---

`FileTranslationService`
------------------------

[](#filetranslationservice)

Handles PHP language files.

Responsibilities:

- file parsing
- `Arr::dot` flattening
- placeholder masking
- pluralization handling
- nested array rebuilding

---

`SmartTranslationService`
-------------------------

[](#smarttranslationservice)

Recursive model translator.

Responsibilities:

- nested JSON traversal
- Filament Builder recursion
- SEO auto-population
- change detection
- HTML chunking
- structural key skipping

---

Logging &amp; Monitoring
========================

[](#logging--monitoring)

All activity is logged to:

```
storage/logs/laravel.log
```

---

Log Events
----------

[](#log-events)

EmojiMessageMeaning🚀Translation Job StartedWorker picked up the job⏭️Skipping Existing TranslationTranslation already exists🌍Translating ChunkActive API request✅Translation CompletedSuccessfully saved⚠️Model Not FoundRecord deleted before execution❌API ErrorProvider failure / timeout---

Failure Recovery
================

[](#failure-recovery)

Failed jobs are stored in Laravel's `failed_jobs` table.

Inspect failures:

```
php artisan queue:failed
```

Retry one job:

```
php artisan queue:retry {id}
```

Retry everything:

```
php artisan queue:retry all
```

---

Performance Optimizations
=========================

[](#performance-optimizations)

LaraGlot is heavily optimized for large-scale applications.

---

Smart Chunking
--------------

[](#smart-chunking)

Large HTML content is automatically split into manageable chunks before translation.

Prevents:

- token overflow
- API payload failures
- malformed responses

---

Concurrent Translation
----------------------

[](#concurrent-translation)

Multiple chunks can be translated simultaneously for significant speed improvements.

---

Change Detection
----------------

[](#change-detection)

LaraGlot detects whether source English content has changed before re-translating.

This avoids:

- unnecessary API usage
- duplicate translations
- wasted queue time

---

Translation Deduplication
-------------------------

[](#translation-deduplication)

If the same phrase appears across:

- Pages
- Posts
- Products
- Language files

…the cached translation is reused globally.

---

License
=======

[](#license)

The MIT License (MIT).

Copyright © 2026 Tonydev.

Built with ❤️ for the Laravel community.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance93

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

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 ~16 days

Total

6

Last Release

8d ago

PHP version history (2 changes)v1.0.0PHP ^8.2

v1.1.3PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/266398964?v=4)[t27124949-cell](/maintainers/t27124949-cell)[@t27124949-cell](https://github.com/t27124949-cell)

---

Top Contributors

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

---

Tags

laravellocalizationi18ntranslationopenaifilamentdeeplgoogle-translateollama

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/tonydev-lara-glot/health.svg)

```
[![Health](https://phpackages.com/badges/tonydev-lara-glot/health.svg)](https://phpackages.com/packages/tonydev-lara-glot)
```

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M132](/packages/laravel-pulse)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k91.9k1](/packages/mike-bronner-laravel-model-caching)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M203](/packages/laravel-ai)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)

PHPackages © 2026

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