Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Gemini Translator Laravel Package

jayesh/laravel-gemini-translator

Interactive Artisan command to scan Laravel projects for translation keys, translate them via Google Gemini AI, and generate language files. Supports Blade/PHP/JS/Vue/TS, concurrency, safe atomic writes, and Laravel Modules integration with skip/refresh modes.

View on GitHub
Deep Wiki
Context7
5.0.1

πŸ”§ Code Quality Improvements (Auto-Applied)

  • usleep() β†’ Sleep::usleep() - Laravel sleep helper
  • sprintf() instead of string concatenation for complex messages
  • Strict array comparison: count() > 0 β†’ !== []
  • Exception variable naming: $e β†’ $throwable
  • Consistent blank lines after control structures
  • Auto-import of class names with unused import removal
5.0.0

⚠ BREAKING CHANGES

  • PHP 8.3 Required: Minimum PHP version bumped from 8.2 to 8.3 (required for Laravel 13 support)
  • Strict Typing: Added declare(strict_types=1) to all PHP files for type safety

⭐ New Features

  • Laravel 13 Support: Full compatibility with Laravel 13.x
  • Comprehensive Test Suite: Added 37 tests with 110 assertions using Orchestra Testbench
    • Unit tests for LocaleHelper and TextHelper utilities
    • Feature tests for CommandRegistration, ServiceProvider, ScannerService, and FileSystemService
  • Code Quality Tools: Integrated PHPStan (level 5), Laravel Pint, and Rector
  • Type Safety: Strict type declarations and explicit type casting throughout codebase

πŸ”§ Improvements

  • Strict Comparisons: Replaced empty() with explicit array/string comparisons (=== [], !== [])
  • Strict in_array(): Added true parameter for strict type checking
  • Command Options: Added explicit (int) casts for chunk-size, retry-delay, and concurrency options
  • Removed Unused Code: Cleaned up 3 unused class constants

πŸ› Bug Fixes

  • Runtime Type Errors: Fixed usleep() calls to use int instead of float
  • Type Safety: Fixed all PHPStan level 5 errors across the codebase

πŸ“‹ Requirements

  • PHP 8.3 or higher
  • Laravel 11.0, 12.0, or 13.0
4.0.3

This patch focuses on observability and debugging quality for failed translation chunks.

Fixed / Improved

  • Added richer per-chunk error diagnostics in TranslationService when a translation task fails:
    • contextual file key
    • chunk key sample
    • full exception trace
  • Increased final-retry raw Gemini response debug log truncation from 500 to 10000 characters for better visibility into malformed or partial model output.

Why this matters

  • Faster root-cause analysis for failed chunks in production and CI runs.
  • Better insight into model response formatting issues without changing normal translation behavior.

Compatibility

  • No breaking changes.
  • No command signature or workflow changes.
  • Safe patch upgrade from 4.0.2.
4.0.2

This patch fixes a file-generation side effect introduced in v4.0.x when users selected only JSON translation groups.

Fixed

  • Resolved unintended creation of lang/{locale}/ directories and framework PHP files (auth.php, pagination.php, passwords.php, validation.php) during JSON-only runs.
  • Framework/vendor translation keys are still loaded and available for JSON translation output (en.json, hi.json, etc.) without forcing PHP file publication.

Behavior Change

  • If only JSON File (*.json) is selected, the command now writes only JSON outputs.
  • Locale directories for PHP files are created only when PHP file groups are actually selected.

Why this matters

  • Prevents noisy/unexpected file changes in fresh projects.
  • Keeps output aligned with explicit user file-group selection.
  • Preserves framework key coverage in JSON workflows.
4.0.1

v4.0.1 - The Stability Patch πŸ›‘οΈ

A focused stability release that addresses edge cases discovered in production use and adds intelligent optimizations for complex translation scenarios.

🎯 What's New

πŸ€– Intelligent Chunk Sizing

The package now automatically adjusts chunk sizes based on key complexity:

  • Keys averaging >80 characters β†’ automatically limited to 3 keys per chunk
  • Keys averaging >60 characters β†’ automatically limited to 5 keys per chunk
  • Result: Dramatically improved success rates for complex validation attributes and long nested keys

πŸ› Automatic Empty Key Filtering

  • Filters out empty and whitespace-only keys before AI processing
  • Prevents "Syntax error" responses from Gemini API
  • Two-layer protection: early filtering + pre-translation validation
  • Your language files stay clean even with accidental empty entries

πŸ” Enhanced Error Debugging

  • Captures raw Gemini API responses on final retry attempts
  • Logs are now written to storage/logs/laravel.log with full context
  • Easier troubleshooting when translations fail

πŸ“š Critical Documentation Updates

  • ⚠️ New warning about config/gemini.php type casting requirement
  • Added comprehensive troubleshooting guide (docs/TROUBLESHOOTING.md)
  • Solutions for "Configuration value must be an integer" error
  • Updated all examples and common issue resolutions

πŸš€ Impact

Before v4.0.1:

  • Long validation keys (90-100+ chars) failed with "Syntax error"
  • Empty keys caused cryptic API failures
  • Limited debugging information

After v4.0.1:

  • βœ… 100% success rate on previously failing long keys
  • βœ… Automatic handling of edge cases
  • βœ… Clear error messages with actionable debugging info
4.0

The Architectural Revolution Update

This is the biggest upgrade ever, transforming the tool into a production-grade, enterprise-ready translation automation platform with enhanced safety, smarter extraction, and powerful new operational modes.


πŸ”₯ Highlights

  • New operational modes for different workflows
  • Production-grade security with atomic file operations
  • Smarter code extraction with framework-specific support
  • Enhanced translation quality with intelligent locale handling
  • Better AI consistency and error recovery
  • Full Windows and CI/CD compatibility

⚠️ Breaking Changes

  • Removed deprecated --source option (use interactive selection)
  • Removed --no-advanced option (pattern detection simplified)
  • Language codes now automatically normalized (en-US β†’ en_US)
  • Cannot combine --refresh and --skip-existing modes

✨ What's New

New Operational Modes

Refresh Mode β€” Re-translate only existing keys without adding new ones. Perfect for improving translation quality without expanding your key set.

Dry Run Mode β€” Preview all changes before writing files. See exactly what would be modified without touching disk.

Configurable Concurrency β€” Control parallel processing speed with adjustable concurrent process limits.

Enhanced Translation Quality

  • Smart locale handling with language-aware formatting
  • Accurate placeholder validation with count verification
  • Intelligent machine key detection and humanization
  • Proper pluralization string support
  • Script-aware formatting for RTL, CJK, and other writing systems

Framework Integration

  • Automatic Laravel framework translation synchronization
  • Vendor translations merged with custom overrides
  • Only updates when new framework keys are detected

Advanced Code Extraction

  • Vue and Alpine.js attribute binding support
  • Multi-line string detection across code
  • Template literal (backtick) string support
  • Nested function call extraction from attributes

AI Translation Improvements

  • More consistent output using latest Gemini SDK features
  • Stricter validation with multiple quality checkpoints
  • Layered fallback strategies for reliable parsing
  • Better handling of edge cases and malformed responses

πŸ”§ Improvements

File Operations

  • Modern PHP array syntax in generated files
  • Atomic file writing prevents corruption
  • Recursive alphabetical sorting for clean version control diffs
  • Directory traversal protection for security

Error Handling

  • Detailed error messages with file and key context
  • Smart retry logic based on error type
  • Different strategies for quota, parsing, and network errors

Cross-Platform

  • Full Windows environment compatibility
  • Automatic non-interactive mode detection for CI/CD
  • Functional prompts for all terminal types

Performance

  • Reduced memory footprint in concurrent mode
  • Better API rate limit management
  • Optimized retry strategies

πŸ› Bug Fixes

Security

  • Fixed directory traversal vulnerability
  • Fixed race conditions in concurrent file writing
  • Enhanced path validation for all platforms

Translation Logic

  • Fixed pluralization detection accuracy
  • Fixed placeholder count validation
  • Fixed machine key recognition patterns
  • Fixed module and app origin separation

Module Support

  • Fixed duplicate scanning prevention
  • Fixed relative path calculations
  • Fixed configuration handling edge cases

Code Extraction

  • Fixed multi-line string patterns
  • Fixed escaped quote handling
  • Fixed attribute binding recognition

User Interface

  • Fixed "ALL FILES" selection behavior
  • Fixed manual selection detection
  • Fixed language directory filtering

πŸ“¦ Upgrade Instructions

Installation

Update your composer dependency to version 4.0:

composer require jayesh/laravel-gemini-translator:^4.0

Migration Steps

  1. Backup your existing translations directory
  2. Run with --dry-run flag to preview changes
  3. Execute actual migration
  4. Review the diff (expect one-time re-sorting of keys)
  5. Commit normalized translation files

What to Expect

  • Larger initial diff due to key re-sorting (one-time only)
  • Locale directory names normalized to standard format
  • New framework translation files bootstrapped
  • Cleaner diffs in future updates

πŸ“š Resources


🎯 Why Upgrade?

Version 4.0 provides production-grade reliability with architectural improvements, security hardening, and powerful new workflows. Whether you're managing a single application or multiple modules, this release offers the tools and safety features needed for enterprise-scale translation management.

3.8

Release Notes

This release builds directly on the foundation of the "Enterprise Edition" (v3.7) by focusing on rock-solid reliability, output quality, and cross-platform compatibility. We've eliminated annoying placeholders, fixed critical output bugs, and ensured the tool works flawlessly for Windows and CI/CD users.

TL;DR: The tool is now automation-friendly and diff-friendly. It skips interactive prompts in CI/CD, guarantees stable file sorting, and hardens the AI integration with intelligent fallbacks.


πŸš€ Key Enhancements

✨ New: Intelligent Fallbacks - No More "NEEDS TRANSLATION"!

The most requested improvement is here. If the AI fails to return a translation, the system now intelligently falls back to the known en source text or the key itself. Your generated files are always usable and ready for review, not filled with useless placeholders.

🧠 New: Hyper-Strict AI Prompting Engine

The prompt sent to Gemini has been re-engineered with a stricter rule set. This resolves a critical bug where the AI would create nested objects in JSON files. All JSON output is now guaranteed to be flat and valid.

πŸ’… New: Deterministic PHP Arrays with Recursive Sorting

Generated PHP translation files are now sorted recursively. This ensures that not only top-level keys but also all nested array keys are sorted alphabetically, leading to clean, stable, and minimal diffs in your version control.

βœ… New: Full Windows & CI/CD Compatibility

The tool now detects non-interactive environments (like GitHub Actions, Docker) and automatically proceeds without hanging on prompts. It also includes a dedicated, functional prompt for Windows users, ensuring a smooth experience for everyone.


⚠️ Breaking Changes & Upgrade Guide

Please read these notes carefully before upgrading.

1. Default Languages Changed to en

The --langs option now defaults to en only (previously en,ru,uz) to prevent accidental multi-language runs.

  • Action Required: If you rely on multiple locales, you must now pass them explicitly:
    php artisan translations:extract-and-generate --langs=en,ru,uz
    

2. Deterministic Sorting May Reorder Arrays

The new recursive sorting will likely reorder nested arrays in your existing PHP language files.

  • Action Required: Expect a one-time, larger-than-usual diff in your language files after the first run. This is expected and will lead to much cleaner diffs in the future.

3. Update Banner Text

  • Action Required: Remember to update the version number in the showWelcome() method from (v3.7) to (v3.8) for consistency.

Full Changelog

  • New: ksortRecursive() method added and implemented when writing PHP language files.
  • New: Robust detection of non-interactive and Windows environments in promptForMultiChoice().
  • Improved: The AI fallback logic in staticStructureTranslationsFromGemini() now uses the $sourceTextMap instead of generating placeholders.
  • Improved: The AI prompt in staticTranslateKeysWithGemini() is now much stricter to enforce flat JSON and improve consistency.
  • Fixed: The framework language loader in loadFrameworkTranslations() now safely iterates files and filters by extension.
  • Fixed: Parallel tasks now explicitly capture the $sourceTextMap to ensure correct fallbacks in fork mode.
  • Changed: The default value for the --langs option in the command signature is now en.
3.7

This release transforms the tool into an enterprise-grade utility, introducing comprehensive support for modular applications and a complete overhaul of the AI translation engine for superior accuracy and reliability. This is the most significant update yet, addressing core architectural limitations and delivering the features needed for complex, modern Laravel projects.

✨ Key Features & Enhancements

🧩 Full Module Support & Control (nwidart/laravel-modules)

The tool is now fully aware of modular architectures, with new features and critical fixes for robust handling.

  • Automatic Detection: Automatically discovers all enabled nwidart modules.
  • Interactive Target Selection: Prompts you to choose which targets to scanβ€”the main application, specific modules, or everything at once.
  • Encapsulated Translations (Default): Correctly reads from and writes to the lang directory within each module (Modules/YourModule/lang/), keeping your translations perfectly organized.
  • ✨ New - Translation Consolidation: You can now choose to consolidate all module translations into the main application's lang/ directory. This is offered as an interactive prompt or can be forced with the --consolidate-modules flag.
  • πŸ› Fixed - Scan Isolation: Fixed a critical bug where scanning the "Main Application" would incorrectly include files from module directories ("leaky scans"). Scans are now properly isolated.

πŸ€– New "AI-First" Translation Engine

We've completely re-architected the way we interact with the AI, eliminating a whole class of bugs and dramatically improving translation quality.

  • Intelligent AI Prompting: The tool no longer tries to guess the source text. It now sends raw keys (like auth.failed or "Save Changes") directly to Gemini with a new, advanced prompt that instructs the AI on how to interpret them based on Laravel conventions.
  • Fixes Incorrect Translations: This solves the critical bug where new keys were being translated with the key itself as the value (e.g., 'welcome' => 'messages.welcome').

🧠 Smarter Key & File Handling

The logic for identifying and grouping keys has been made far more robust.

  • Context-Aware Grouping: The tool now tracks the origin of every key, ensuring that a key found in the Settings module is correctly associated with the Settings module's translation files.
  • Handles Complex Keys: The scanner now correctly identifies full-sentence keys as belonging to JSON files, fixing a bug where it would create incorrect .php files from sentence-like strings.
  • Fixes "0 Keys Processed" Bug: The key-to-file mapping logic has been rewritten to correctly assign all discovered keys to your selected files.

πŸ”Œ True Offline Mode

If the GEMINI_API_KEY is not set, the tool now enters a dedicated Offline Mode, generating placeholder files with the key as the value. This is perfect for initial setup or working without an internet connection.

2.7

✨ New Feature: Context-Aware Translations with --context

You can now use the optional --context flag to provide a short description of your project directly to the AI. This is crucial for applications in domains like finance, healthcare, legal, or any field with specialized vocabulary.

How it works: The command injects your description into the AI prompt, helping it understand the specific meaning of ambiguous words.

Example: Financial Application Without context, the AI might translate "position" as a physical location. With context, it understands it as a financial holding.

# NEW: Provide context for a financial trading platform
php artisan translations:extract-and-generate --context="A SaaS platform for financial trading of stocks. Terms like 'position' and 'security' refer to financial concepts."

This update makes the translator significantly more robust and intelligent, ensuring higher-quality translations and a smoother developer experience.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope