PHPackages                             josemontano1996/laravel-localization-suite - 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. josemontano1996/laravel-localization-suite

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

josemontano1996/laravel-localization-suite
==========================================

A comprehensive, runtime-safe localization suite for Laravel 12+, with first-class support for Octane, Swoole and OpenSwoole concurrency hooks.

v0.2.0-alpha(2mo ago)10MITPHPPHP ^8.4CI passing

Since Feb 28Pushed 2mo agoCompare

[ Source](https://github.com/josemontano1996/laravel-localization-suite)[ Packagist](https://packagist.org/packages/josemontano1996/laravel-localization-suite)[ Docs](https://github.com/josemontano1996/laravel-localization-suite)[ RSS](/packages/josemontano1996-laravel-localization-suite/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (11)Versions (4)Used By (0)

Laravel Localization Suite
==========================

[](#laravel-localization-suite)

A comprehensive, runtime safe, localization package for Laravel 12+ with first-class driver support for **Laravel Octane**, **Swoole** and **OpenSwoole** concurrency hooks.

Localize your laravel app without having to worry about the runtime your app will run on, FPM, Octane, or even Octane with Swoole or OpenSwoole asynchronous hooks, just change the localization driver and you will get a worry free localized app.

[![PHP Version](https://camo.githubusercontent.com/504ead6a583c68d8d62d7bfceed24e569ca613d7a36bed380281b3455b5c7b31/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e342d626c7565)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/53f994a897d083946738e0bc5943400cc950fa40f004eb4ba44bc2385b2f45ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d31322e782d726564)](https://laravel.com)

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

[](#-features)

- **Driver-based architecture** — Swap between Native, Context, Swoole, or OpenSwoole drivers depending on your needs.
- **Octane-ready** — Octane-safe drivers grant locale isolation preventing cross-request bleed
- **Concurrency safe drivers** — Swoole and OpenSwoole drivers are completely concurrency safe, meaning they support multiple concurrent requests per worker and they support all Swoole based HOOKS.
- **Localized routing** — Simple locale-prefixed route groups with automatic detection
- **Middlewares** - Useful middlewares for smart locale detection with metadata integration for best SEO practices
- **Blade directives** — `@t`, `@route`, `@locale`, `@currency`, `@date` and more
- **Macros** — `redirect()->localized()`, `Route::localized()`, `URL::withLocale()`
- **Validation** — Context-aware validation messages without touching global state

---

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

[](#-installation)

```
composer require josemontano1996/laravel-localization-suite
```

Publish the configuration:

```
php artisan vendor:publish --tag=localization-config
```

---

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

[](#️-configuration)

Drivers
-------

[](#drivers)

### PHP Version Support Matrix

[](#php-version-support-matrix)

DriverPHP 8.4PHP 8.5Per Worker Concurrency Safe`native`✅✅❌`context`✅✅❌`swoole`✅❌✅`openswoole`✅❌✅> **Note:** Swoole and OpenSwoole do not yet support PHP 8.5. Use `native` or `context` drivers for PHP 8.5 environments.

For a detailed explanation of all available drivers, their concurrency guarantees, and how to implement your own, see the [Drivers Documentation](docs/DRIVERS.md).

### `config/localization.php`

[](#configlocalizationphp)

```
return [
    /*
    |--------------------------------------------------------------------------
    | Localization Driver
    |--------------------------------------------------------------------------
    |
    | Built-in Drivers:
    |  - "native": Standard Laravel behavior.
    |  - "context": Laravel 11+ Context.
    |  - "swoole": Swoole Coroutine Context (concurrency safe).
    |  - "openswoole": OpenSwoole Coroutine Context (concurrency safe).
    |
    | Custom Drivers:
    | You may provide a fully qualified class name implementing:
    | \Josemontano1996\LaravelLocalizationSuite\Contracts\LocalizationDriverContract
    |
    */
    'driver' => env('LOCALIZATION_DRIVER', 'native'),

    // Route parameter name for the locale segment
    'route_key' => 'locale',
];
```

### Required Laravel Configuration

[](#required-laravel-configuration)

Add these to your `config/app.php`:

```
'locale' => 'en',
'fallback_locale' => 'en',
'supported_locales' => ['en', 'es', 'fr', 'de'], // Required!
```

Important

The `supported_locales` array **must** be populated with at least one locale.

---

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

[](#-quick-start)

### 1. Define Localized Routes

[](#1-define-localized-routes)

```
// routes/web.php
use Illuminate\Support\Facades\Route;

Route::localized()
    ->middleware('localization')
    ->group(function () {
        Route::get('/', fn () => view('home'))->name('home');
        Route::get('/about', fn () => view('about'))->name('about');
    });
```

This creates routes like:

- `/en/`, `/es/`, `/fr/`
- `/en/about`, `/es/about`, `/fr/about`

### 2. Use in Controllers

[](#2-use-in-controllers)

```
use Localization;

class HomeController extends Controller
{
    public function index()
    {
        // Get current locale
        $locale = Localization::getCurrentLocale();

        // Translate with context-aware locale
        $greeting = Localization::t('messages.welcome');

        // Generate localized route URL
        $aboutUrl = Localization::route('about');

        return view('home', compact('greeting', 'aboutUrl'));
    }
}
```

### 3. Use in Blade Templates

[](#3-use-in-blade-templates)

```
{{-- Current locale --}}

{{-- Translations --}}
@t('messages.welcome')
@t('messages.greeting', ['name' => $user->name])

{{-- Pluralization --}}
@tchoice('messages.items', $count)

{{-- Localized routes --}}
{{ t('nav.about') }}
{{ $product->name }}

{{-- Formatting --}}
@number(1234.56)          {{-- 1,234.56 or 1.234,56 depending on locale --}}
@currency(99.99, 'EUR')   {{-- €99.99 or 99,99 € --}}
@percent(0.15)            {{-- 15% --}}

{{-- Dates --}}
@date($post->created_at)           {{-- January 15, 2025 --}}
@datetime($post->created_at)       {{-- January 15, 2025 at 3:45 PM --}}
@date($post->created_at, 'MMMM YYYY') {{-- Custom format --}}

{{-- Conditionals --}}
@localeIs('en')
    English-specific content
@elselocaleIs('es')
    Contenido en español
@endlocaleIs

{{-- Language switcher --}}

    @locales($lang)
        getCurrentLocale()) class="active" @endif>
            {{ strtoupper($lang) }}

    @endlocales

```

---

🛣️ Routing
----------

[](#️-routing)

### Localized Route Groups

[](#localized-route-groups)

```
Route::localized()
    ->middleware('localization')
    ->group(function () {
        // All routes here will be prefixed with /{locale}/
        Route::get('/', HomeController::class)->name('home');
        Route::get('/products', [ProductController::class, 'index'])->name('products.index');
    });
```

### Middleware

[](#middleware)

The package provides a `localization` middleware group that:

1. **Detects locale from URL** — Reads the `{locale}` route parameter
2. **Validates locale** — Redirects to best match if unsupported, falling back to smart request preferred locales.
3. **Sets response headers** — Adds `Content-Language` header

```
// Individual middleware aliases available:
Route::middleware('localization.from_route'); // Set locale from URL
Route::middleware('localization.headers');     // Add Content-Language header
Route::middleware('localization');             // Both combined
```

### Generate Localized URLs

[](#generate-localized-urls)

```
// Using the service
localization()->route('products.show', ['product' => $product]);

// Using URL macro
URL::localeRoute('products.show', ['product' => $product]);

// Generate URL with a different locale
URL::withLocale('es'); // Same page but in Spanish
```

---

🔄 Redirects
-----------

[](#-redirects)

The `redirect()->localized()` macro ensures all redirects respect the current locale:

```
// Redirect to a named route (locale is injected automatically)
return redirect()->localized()->route('dashboard');

// Redirect to a path (locale is prefixed automatically)
return redirect()->localized()->to('/profile');

// Redirect back with locale fallback
return redirect()->localized()->back();

// Redirect to intended URL after authentication
return redirect()->localized()->intended('/dashboard');

// Localized signed routes
return redirect()->localized()->signedRoute('unsubscribe', ['user' => $user]);

// Controller actions
return redirect()->localized()->action([UserController::class, 'show'], ['id' => 1]);

// External URLs (bypasses localization)
return redirect()->localized()->away('https://google.com');
```

---

🌐 Request Helpers
-----------------

[](#-request-helpers)

```
// Get current locale
$locale = request()->locale();

// Get browser's accepted locales
$accepted = request()->acceptedLocales(); // ['en' => 1.0, 'es' => 0.8, ...]

// Get best matching locale from supported list
$preferred = request()->preferredLocale(['en', 'es', 'fr']); // 'en'
```

---

🔧 Drivers
---------

[](#-drivers)

### Native Driver (Default)

[](#native-driver-default)

Uses Laravel's built-in `App::setLocale()`. Safe for traditional FPM/mod\_php.

```
LOCALIZATION_DRIVER=native
```

### Context Driver

[](#context-driver)

Uses Laravel 11+ `Context` facade for request-isolated state. This is safe for regular Octane environments.

```
LOCALIZATION_DRIVER=context
```

### Swoole Driver

[](#swoole-driver)

Uses Swoole's coroutine context. Required when enabling HOOKS\_ALL flag for true per worker concurrency in **Laravel Octane with Swoole**.

```
LOCALIZATION_DRIVER=swoole
```

### OpenSwoole Driver

[](#openswoole-driver)

Uses OpenSwoole's coroutine context. Required when enabling HOOKS\_ALL flag for true per worker concurrency in **Laravel Octane with OpenSwoole**.

```
LOCALIZATION_DRIVER=openswoole
```

### Custom Driver

[](#custom-driver)

Implement `LocalizationDriverContract`:

```
use Josemontano1996\LaravelLocalizationSuite\Contracts\LocalizationDriverContract;

class MyCustomDriver implements LocalizationDriverContract
{
    public function getCurrentLocale(): ?string
    {
        // Return stored locale or null
    }

    public function setCurrentLocale(string $locale): void
    {
        // Store the locale
    }

    public function isSafeToMutateGlobalState(): bool
    {
        // Return true if driver environment allows/desires the application to know if it's safe to mutate global state (App locale, Carbon, etc.)
        return false;
    }
}
```

```
// config/localization.php
'driver' => \App\Drivers\MyCustomDriver::class,
```

---

📚 API Reference
---------------

[](#-api-reference)

### `localization()` Helper

[](#localization-helper)

MethodDescription`getCurrentLocale(): string`Get the current request locale`setCurrentLocale(string $locale): void`Set the locale for the current request`getConfigLocale(): string`Get the configured default locale`getSupportedLocales(): array`Get list of supported locales`getRouteKey(): string`Get the route parameter name (default: `locale`)`route($name, $params, $absolute): string`Generate localized route URL`t($key, $replace, $locale): string`Translate a string`tchoice($key, $number, $replace, $locale): string`Pluralized translation`formatNumber($value, $style, $options): string`Format number/currency/percent### Blade Directives

[](#blade-directives)

DirectiveUsage`@locale`Output current locale`@t('key')`Translate string`@t('key', ['name' => $value])`Translate with replacements`@tchoice('key', $count)`Pluralized translation`@route('name')`Localized route URL`@route('name', $params)`Localized route with parameters`@number($value)`Locale-formatted number`@currency($value, 'USD')`Locale-formatted currency`@percent($value)`Locale-formatted percentage`@date($date)`Locale-formatted date`@date($date, 'MMMM YYYY')`Date with custom format`@datetime($date)`Locale-formatted date and time`@localeIs('en')`Conditional for locale`@locales($var)` / `@endlocales`Loop through supported locales### Facade

[](#facade)

```
use Localization;

Localization::getCurrentLocale();
Localization::route('home');
Localization::t('messages.welcome');
```

---

🧪 Testing
---------

[](#-testing)

```
composer test       # Run tests
composer lint       # Run PHP Pint
composer analyse    # Run PHPStan
```

---

📚 Detailed Documentation
------------------------

[](#-detailed-documentation)

- [Drivers Documentation](docs/DRIVERS.md): In-depth guide to all available drivers, concurrency, and custom driver implementation.
- [Middleware Documentation](docs/MIDDLEWARES.md): Learn about the provided middlewares and how to use them for locale detection and headers.
- [Blade Directives Documentation](docs/BLADEDIRECTIVES.md): Learn about the blade directives.
- [Macros Documentation](docs/MACROS.md): Learn about the package macros.

---

📄 License
---------

[](#-license)

MIT License. See [LICENSE](LICENSE.md) for details.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! See [CONTRIBUTING](CONTRIBUTING.md) for details.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance86

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

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

Total

2

Last Release

72d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/486c6e568f76f9f0fa5616f4b8f2c99c4a3e84133aa028c36f0d0ae6ed97a5a6?d=identicon)[josemontano1996](/maintainers/josemontano1996)

---

Top Contributors

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

---

Tags

concurrencyconcurrency-safefpmi18nlaravellaravel-octanelaravel-packagelocalizationoctaneopenswoolephpphp-librarystateswooleconcurrencylaravellocalizationi18nswooleoctaneopenswoolestate-isolation

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/josemontano1996-laravel-localization-suite/health.svg)

```
[![Health](https://phpackages.com/badges/josemontano1996-laravel-localization-suite/health.svg)](https://phpackages.com/packages/josemontano1996-laravel-localization-suite)
```

###  Alternatives

[outhebox/laravel-translations

Manage your Laravel translations with a beautiful UI. Add, edit, delete, import, and export translations with ease.

80687.6k](/packages/outhebox-laravel-translations)[erag/laravel-lang-sync-inertia

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

3812.2k](/packages/erag-laravel-lang-sync-inertia)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

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