laraveledge/laravel-locale
Composer 安装命令:
composer require laraveledge/laravel-locale
包简介
Elegant URL-based locale handler and middleware for Laravel.
README 文档
README
Elegant URL-Based Localization for Laravel Applications
Laravel Locale is a simple yet powerful package for handling localization through URL segments in Laravel. It detects, validates, and manages locale slugs (e.g., /en, /tr) in the request path, with seamless support for session storage, normalization, and middleware-based behavior.
📚 Table of Contents
- 🚀 Installation
- ⚙️ Configuration
- 🧩 Usage
- 📌 Alias Usage
- 🚦 Middleware Setup
- 🧠 Locale Detection Order
- ⚠️ Edge Cases
- ✅ What This Package Does
- 📁 Folder Structure
- ✅ Requirements
- 📄 License
🚀 Installation
Install via Composer:
composer require laraveledge/laravel-locale
⚙️ Configuration
Publish the configuration file:
php artisan vendor:publish --tag=laravel-locale-config
This will publish config/locale.php, where you can specify your supported locales:
return [ 'supported_locales' => ['en', 'tr', 'ur'], ];
🧩 Usage
Wrap your localized routes using middleware and a {locale} prefix:
use Laraveledge\LaravelLocale\Middleware\SetLocale; use Laraveledge\LaravelLocale\Middleware\EnsureIsLocale; use Laraveledge\LaravelLocale\Middleware\SetDefaultLocaleForUrls; Route::group([ 'prefix' => '{locale}', 'middleware' => [ EnsureIsLocale::class, SetLocale::class, SetDefaultLocaleForUrls::class, 'web', ], ], function () { Route::get('/', fn () => 'Home Page')->name('home'); Route::get('/about', fn () => 'About Page'); Route::get('/test', fn () => 'Test Page')->name('test'); Route::fallback(function () { abort(404, 'Hm, why did you land here somehow?'); }); //Neccessary , why ? see Edge Cases below });
Now visit /, /about, or /test to be redirected to the localized versions.
📌 Alias Usage
You can also register aliases in bootstrap/app.php to avoid referencing class paths directly:
use Laraveledge\LaravelLocale\Middleware\SetLocale; use Laraveledge\LaravelLocale\Middleware\EnsureIsLocale; use Laraveledge\LaravelLocale\Middleware\SetDefaultLocaleForUrls; ->withMiddleware(function (Middleware $middleware): void { $middleware->alias([ 'ensureIsLocale' => EnsureIsLocale::class, 'redirectMissingLocale' => RedirectMissingLocale::class, 'setDefaultUrls' => SetDefaultLocaleForUrls::class, 'setLocale' => SetLocale::class, ]); });
🚦 Middleware Setup
To avoid conflicts with Laravel’s internal URL binding, make sure to set middleware priority properly:
use Illuminate\Routing\Middleware\SubstituteBindings; ->withMiddleware(function (Middleware $middleware) { $middleware->prependToPriorityList( before: SubstituteBindings::class, prepend: SetDefaultLocaleForUrls::class, ); });
🚦 Full Setup (Copy Paste) - Recommended:
bootstrap/app.php: use Illuminate\Routing\Middleware\SubstituteBindings; use Laraveledge\LaravelLocale\Middleware\SetLocale; use Laraveledge\LaravelLocale\Middleware\EnsureIsLocale; use Laraveledge\LaravelLocale\Middleware\SetDefaultLocaleForUrls; ->withMiddleware(function (Middleware $middleware): void { $middleware->prependToPriorityList( before: SubstituteBindings::class, prepend: SetDefaultLocaleForUrls::class, ); $middleware->alias([ 'ensureIsLocale' => EnsureIsLocale::class, 'setDefaultUrls' => SetDefaultLocaleForUrls::class, 'setLocale' => SetLocale::class, ]); }) web.php: Route::group([ 'prefix' => '{locale}', 'middleware' => ['web', 'ensureIsLocale', 'setLocale', 'setDefaultUrls'] // ensure this middleware order ], function () { Route::get('/', function () { return 'home'; }); Route::get('/about', function () { return 'products'; }); Route::get('/test', function(){ return 'test'; })->name('test'); //ensure a route named test is present in your routes so you can check/test the Locale::debug() mnethod Route::fallback(function () { abort(404, 'Hm, why did you land here somehow?'); }); //Neccessary , why ? see Edge Cases below });
🧠 Locale Detection Order
The package detects locale using the following order:
- Session – If a locale exists in session, it is used.
- URL Segment – First segment of the path.
- Browser Preferred Language – Based on
Accept-Languageheader. - Fallback Locale – As defined in
app.fallback_locale.
⚠️ Edge Cases
- If your route is deeply nested like /products/1 and the locale is missing, Laravel may return a 404 before your middleware is ever triggered. This happens because Laravel tries to match the route as-is (e.g., /products/1), but it doesn't exist without a {locale} prefix, so it aborts with a 404 before even hitting the middleware stack.
- However, if you define a Route::fallback() inside your localized group, Laravel is then forced to execute the fallback when no route matches. This allows the middleware to still kick in and redirect appropriately.
- Without a fallback, shallow routes like /products will still work because Laravel can find a matching route and then the middleware handles it. But deep, parameterized routes like /products/1 will fail silently unless the fallback is present.
✅ Solution: Always define a Route::fallback() within your {locale} route group to ensure nested and parameterized routes also get redirected when the locale is missing.
Route::fallback(function () { abort(404, 'Hm, why did you land here somehow?'); }); ---
✅ What This Package Does
- ✅ Detects and validates the locale segment in the URL
- 🔠 Normalizes casing (e.g.,
EN-us→en) - 💾 Stores the selected locale in session
- 🌍 Calls
App::setLocale(...) - 🔁 Redirects to localized URLs if missing or invalid
🙌 Inspired by the Greats — Built with Simplicity
This package is inspired by:
These packages have served the Laravel ecosystem well and offer a wide range of features. However, as Laravel modernized its routing and middleware pipeline, we felt the need for a simpler, lighter, and middleware-first approach — without route macros or runtime route manipulation.
🎯 Why This Package Exists
In real-world projects:
mcamaradynamically registers routes at runtime, which can introduce unpredictable behavior and confusion.codezerouses route macros and abstractions which deviate from native Laravel patterns.
This package solves that by offering:
✅ Clean, Laravel-native routing
✅ No macros — just plain Route::get() and Route::group()
✅ Middleware-first lifecycle control
✅ SEO-optimized URL redirection and normalization
✅ Works great with Livewire, Inertia, Blade, APIs, SPAs
✅ Debug-friendly (Locale::debug())
✅ Lightweight, transparent, and easy to extend
📦 What This Package Is (and Isn't)
This package intentionally starts simple.
It currently does not offer some of the advanced features available in mcamara or codezero such as:
- Automatic route translation
- Locale-prefixed route generation
- URL version negotiation, etc.
We plan to add more features in future versions — while staying true to the Laravel philosophy of clarity over magic.
🧠 Choose Based on Your Needs
|-----------------------------------|----------------------------------------| | You Should Use This Package If...| |-----------------------------------|----------------------------------------| | You want a lightweight, zero-config localization system | You prefer Laravel-native routes with no macros | You value predictable middleware-based flow | You’re building something new and modern |-----------------------------------|----------------------------------------| | You Might Prefer Other Packages If... | |-----------------------------------|----------------------------------------| | You need automatic route translation | You don’t mind learning route macros | You need deeply integrated i18n features | You’re maintaining legacy systems
🚀 Just Use It — You’ll Feel the Difference
Install it, add middleware, define routes — and you’re done.
Route::group([ 'prefix' => '{locale}', 'middleware' => ['web', 'ensureIsLocale', 'setLocale', 'setDefaultUrls'] ], function () { Route::get('/', fn () => view('home'))->name('home'); });
📁 Folder Structure
src/
├── Config/
│ └── locale.php
├── Middleware/
│ ├── EnsureIsLocale.php
│ ├── SetLocale.php
│ └── SetDefaultLocaleForUrls.php
├── Services/
│ └── LocaleService.php
├── Facades/
│ └── Locale.php (optional)
└── LaravelLocaleServiceProvider.php
✅ Requirements
- PHP 8.1+
- Laravel 10+
📄 License
This package is open-source and released under the MIT License.
laraveledge/laravel-locale 适用场景与选型建议
laraveledge/laravel-locale 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 9 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 07 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「routing」 「php」 「translation」 「locale」 「routes」 「language」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 laraveledge/laravel-locale 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 laraveledge/laravel-locale 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 laraveledge/laravel-locale 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A custom URL rule class for Yii 2 which allows to create translated URL rules
A Laravel Eloquent model trait for translatable resource
Write down your routing mapping at one place
Bureaux A Partager Edit - Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.
Symfony localise.biz library
统计信息
- 总下载量: 9
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 8
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-03