### Install Laravel Localization
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Installs the laravel-localization package using Composer.
```bash
composer require mcamara/laravel-localization
```
--------------------------------
### Custom Configuration Service Provider
Source: https://github.com/mcamara/laravel-localization/blob/master/ADDITIONS.md
Example of a custom service provider to configure Laravel Localization settings, such as supported locales, using the `config()` helper.
```php
[
'ace' => array( 'name' => 'Achinese', 'script' => 'Latn', 'native' => 'Aceh' ),
'ca' => array( 'name' => 'Catalan', 'script' => 'Latn', 'native' => 'català' ),
'en' => array( 'name' => 'English', 'script' => 'Latn', 'native' => 'English' ),
],
'laravellocalization.useAcceptLanguageHeader' => true,
'laravellocalization.hideDefaultLocaleInURL' => true
]);
}
}
```
--------------------------------
### Localized Route Group Example
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Demonstrates how to group routes to support localization by prefixing them with the current locale obtained from LaravelLocalization::setLocale().
```php
// routes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function()
{
/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
Route::get('/', function()
{
return View::make('hello');
});
Route::get('test',
function(){
return View::make('test');
});
});
/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
```
--------------------------------
### Get Clean URL
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns a URL that is clean of any localization information. For example, it would return `/about` for an input like `/es/about`.
```php
// Returns /about
{{ LaravelLocalization::getNonLocalizedURL('/es/about') }}
```
--------------------------------
### Custom LaravelLocalization Implementation with Dependency Injection
Source: https://github.com/mcamara/laravel-localization/blob/master/UPGRADING.md
Demonstrates how to extend the LaravelLocalization class and utilize dependency injection for its constructor. This is useful for custom implementations that require access to Laravel's core services.
```php
use McamaraLaravelLocalizationLaravelLocalization;
use IlluminateContractsConfigRepository as ConfigRepository;
use IlluminateContractsFoundationApplication;
use IlluminateContractsRoutingUrlGenerator;
use IlluminateContractsTranslationTranslator;
use IlluminateHttpRequest;
use IlluminateRoutingRouter;
class MyLaravelLocalization extends LaravelLocalization
public function __construct(
mixed $myCustomVariable,
Application $app,
ConfigRepository $configRepository,
Translator $translator,
Router $router,
Request $request,
UrlGenerator $url
) {
parent::__construct($app, $configRepository, $translator, $router, $request, $url);
}
}
```
--------------------------------
### Get Supported Locales Keys
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns an array containing only the keys of all supported locales.
```php
{{ LaravelLocalization::getSupportedLanguagesKeys() }}
```
--------------------------------
### Register Service Provider and Facade (Laravel 5.4 and below)
Source: https://github.com/mcamara/laravel-localization/blob/master/ADDITIONS.md
This snippet shows how to register the Laravel Localization service provider and its corresponding facade in the `config/app.php` file for older Laravel versions.
```php
'providers' => [
// [...]
Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,
],
```
```php
'aliases' => [
// [...]
'LaravelLocalization' => Mcamara\LaravelLocalization\Facades\LaravelLocalization::class,
]
```
--------------------------------
### Get Supported Locales
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns an array containing all supported locales and their associated properties.
```php
{{ LaravelLocalization::getSupportedLocales() }}
```
--------------------------------
### Language Selector Blade Component
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Provides a Blade template example for creating a language selector. It iterates through supported locales and generates links using `LaravelLocalization::getSupportedLocales()` and `LaravelLocalization::getLocalizedURL()`.
```blade
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
```
--------------------------------
### Updating Singleton Binding for LaravelLocalization
Source: https://github.com/mcamara/laravel-localization/blob/master/UPGRADING.md
Shows the change in binding the LaravelLocalization singleton in the service container from v1 to v2. The v2 approach simplifies the binding process by directly referencing the class name.
```diff
use McamaraLaravelLocalizationLaravelLocalization;
-$this->app->singleton(LaravelLocalization::class, function () {
- return new MyLaravelLocalization();
-});
+$this->app->singleton(LaravelLocalization::class, MyLaravelLocalization::class);
```
--------------------------------
### Get Localized URL for Specific Locale
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Retrieves the current URL localized to a specific locale. For example, it returns the current URL with the English locale.
```php
// Returns current url with English locale.
{{ LaravelLocalization::getLocalizedURL('en') }}
```
--------------------------------
### Get Supported Locales Custom Order
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns all supported locales, ordered according to the configuration file. This is useful for creating language selectors.
```php
{{ LaravelLocalization::getLocalesOrder() }}
```
--------------------------------
### Get Current Locale
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns the key of the currently active locale.
```php
{{ LaravelLocalization::getCurrentLocale() }}
```
--------------------------------
### Get Current Locale Script
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns the ISO 15924 script code for the current locale (e.g., Latn, Cyrl, Arab).
```php
{{ LaravelLocalization::getCurrentLocaleScript() }}
```
--------------------------------
### Get Current Locale Name
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns the display name of the current locale (e.g., English, Spanish, Arabic).
```php
{{ LaravelLocalization::getCurrentLocaleName() }}
```
--------------------------------
### Get Current Locale Direction
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns the text directionality of the current locale (ltr for left-to-right, rtl for right-to-left).
```php
{{ LaravelLocalization::getCurrentLocaleDirection() }}
```
--------------------------------
### Get Current Locale Regional Name
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns the regional name of the current locale (e.g., en_GB, en_US, fr_FR).
```php
{{ LaravelLocalization::getCurrentLocaleRegional() }}
```
--------------------------------
### Setup Route Caching for Laravel Localization (After Laravel 11)
Source: https://github.com/mcamara/laravel-localization/blob/master/CACHING.md
For Laravel 11 and later, use the `CachedTranslatedRouteLoader` class within the `register` method of your `AppServiceProvider` and configure `loadCachedRoutesUsing` in the `boot` method.
```php
$this->loadCachedRoutes());
...
}
```
--------------------------------
### Get Current Locale Native Name
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns the native display name of the current locale (e.g., English, Español, عربى).
```php
{{ LaravelLocalization::getCurrentLocaleNative() }}
```
--------------------------------
### Setup Route Caching for Laravel Localization (Before Laravel 11)
Source: https://github.com/mcamara/laravel-localization/blob/master/CACHING.md
For Laravel versions prior to 11, integrate the `LoadsTranslatedCachedRoutes` trait into your `RouteServiceProvider` to enable caching of translated routes.
```php
```
--------------------------------
### Get URL from Route Name Translated
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Returns a route localized to the desired locale using a translation key. If the translation key does not exist for the specified locale, it returns false. It supports route model binding and translated routes.
```php
// Returns /es/acerca
{{ LaravelLocalization::getURLFromRouteNameTranslated('es', 'routes.about') }}
```
```php
// An array of attributes can be provided.
// Returns /en/archive/ghosts, /fr/archive/fantômes, /pt/arquivo/fantasmas, etc.
Ghost Stories
```
--------------------------------
### Get Localized URL
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Generates a localized URL for a given path, taking into account route model binding, hideDefaultLocaleInURL, and Translated Routes settings. If the current locale is Spanish, it returns `/es/test` for the input `/test`.
```php
// If current locale is Spanish, it returns `/es/test`
@lang('Follow this link')
```
--------------------------------
### Publish Configuration File
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Publishes the configuration file for laravel-localization to allow customization.
```bash
php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"
```
--------------------------------
### Laravel Localization Configuration Options
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Details the available configuration options for the laravel-localization package, including supported locales, browser language detection, URL formatting, and locale ordering.
```APIDOC
Configuration Options:
- supportedLocales: Defines the languages supported by the application. Defaults to English and Spanish.
- useAcceptLanguageHeader: If true, automatically detects the user's language from the browser's Accept-Language header.
- hideDefaultLocaleInURL: If true, the default locale will not be displayed in the URL.
- localesOrder: Allows specifying a custom order for the languages.
- localesMapping: Enables renaming of locales in the URL.
- utf8suffix: Allows changing the utf8suffix, useful for certain server configurations like CentOS.
- urlsIgnored: A list of specific URLs to ignore for localization.
```
--------------------------------
### Testing with Locale Management
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Provides helper methods for `TestCase.php` to refresh the application with a specific locale and demonstrates how to use these helpers in tests to ensure correct route resolution and language handling.
```php
// TestCase.php
protected function refreshApplicationWithLocale($locale)
{
self::tearDown();
putenv(LaravelLocalization::ENV_ROUTE_KEY . '=' . $locale);
self::setUp();
}
protected function tearDown(): void
{
putenv(LaravelLocalization::ENV_ROUTE_KEY);
parent::tearDown();
}
// YourTest.php
public function testBasicTest()
{
$this->refreshApplicationWithLocale('en');
// Testing code
}
```
--------------------------------
### Integrating Translated Routes in web.php
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Shows how to integrate the translated routes into your `routes/web.php` file using a route group with the `localize` middleware and `LaravelLocalization::transRoute()` helper to dynamically load translated route segments.
```php
Route::group(['prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localize' ]], function () {
Route::get(LaravelLocalization::transRoute('routes.about'), function () {
return view('about');
});
Route::get(LaravelLocalization::transRoute('routes.article'), function (\App\Article $article) {
return $article;
});
//,...
});
```
--------------------------------
### Caching Localized Routes
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Provides the Artisan command to cache localized routes. It also explains the necessary adjustments to `RouteServiceProvider` for caching to work correctly in different Laravel versions.
```bash
php artisan route:trans:cache
```
--------------------------------
### Listening for Route Translation Events
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Shows how to listen for the 'routes.translation' event to capture and potentially translate URL parameters. This is useful for scenarios where route parameters themselves need to be localized.
```php
Event::listen('routes.translation', function($locale, $attributes)
{
// Do your magic
return $attributes;
});
```
--------------------------------
### Route Group with Middleware
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Shows how to apply specific localization middleware to a route group, ensuring proper redirection and locale handling.
```php
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function(){ //...
});
```
--------------------------------
### Register Middleware in bootstrap/app.php (Laravel 11+)
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Registers the package's middleware aliases within the application configuration for Laravel 11 and newer versions.
```php
return Application::configure(basePath: dirname(__DIR__))
// Other application configurations
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
/**** OTHER MIDDLEWARE ALIASES ****/
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class,
]);
})
```
--------------------------------
### Register Middleware in app/Http/Kernel.php
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Registers the package's middleware aliases within the application's HTTP kernel for older Laravel versions.
```php
\Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
];
}
```
--------------------------------
### Translated Routes Configuration
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Illustrates how to define translated routes by creating language-specific `routes.php` files within the `resources/lang` directory (or `lang` directory in Laravel 9+). These files map route keys to their translated URL segments.
```php
"about",
"article" => "article/{article}",
];
```
```php
"acerca",
"article" => "articulo/{article}",
];
```
--------------------------------
### Route Model Binding with Translated Slugs
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Demonstrates how to override the `resolveRouteBinding` method in a model to find a model based on a translated slug. This ensures that route model binding works correctly with localized URLs.
```php
public function resolveRouteBinding($slug)
{
return static::findByLocalizedSlug($slug)->first() ?? abort(404);
}
```
--------------------------------
### Route Caching Configuration (Laravel < 11)
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Illustrates how to use the `LoadsTranslatedCachedRoutes` trait in `RouteServiceProvider` for versions of Laravel prior to 11 to enable localized route caching.
```php
[
'en-GB' => 'uk'
],
// ... other configurations
];
```
--------------------------------
### Implementing LocalizedUrlRoutable for Translatable Parameters
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Explains the implementation of the `LocalizedUrlRoutable` interface within a model to support translatable route parameters. The `getLocalizedRouteKey($locale)` method should return the appropriate slug for a given locale.
```php
$this->slug_en,
'es' => $this->slug_es,
];
return $translatedSlugs[$locale] ?? $this->slug;
}
}
```
--------------------------------
### Route Caching Configuration (Laravel >= 11)
Source: https://github.com/mcamara/laravel-localization/blob/master/README.md
Demonstrates the updated approach for Laravel 11 and later, where `CachedTranslatedRouteLoader` is used in `AppServiceProvider` to manage localized route caching.
```php
$this->loadCachedRoutes());
...
}
```
--------------------------------
### List Translated Routes
Source: https://github.com/mcamara/laravel-localization/blob/master/CACHING.md
View the cached routes for a specific locale by using the `php artisan route:trans:list {locale}` command, providing the desired locale code as an argument.
```bash
php artisan route:trans:list {locale}
# for instance:
php artisan route:trans:list en
```
--------------------------------
### Cache Translated Routes
Source: https://github.com/mcamara/laravel-localization/blob/master/CACHING.md
Use the `php artisan route:trans:cache` command to cache all translated routes for your application. This replaces the standard `php artisan route:cache` command.
```bash
php artisan route:trans:cache
```
--------------------------------
### Clear Cached Translated Routes
Source: https://github.com/mcamara/laravel-localization/blob/master/CACHING.md
Remove all cached translated routes using the `php artisan route:trans:clear` command. Alternatively, `php artisan route:clear` can be used, though it may leave residual files.
```bash
php artisan route:trans:clear
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.