在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):mcamara/laravel-localization开源软件地址(OpenSource Url):https://github.com/mcamara/laravel-localization开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):Laravel LocalizationEasy i18n localization for Laravel, an useful tool to combine with Laravel localization classes. The package offers the following:
Table of Contents
Laravel compatibility
InstallationInstall the package via composer: For Laravel 5.4 and below it necessary to register the service provider. Config FilesIn order to edit the default configuration you may execute:
After that, The configuration options are:
Register MiddlewareYou may register the package middleware in the <?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
/**** OTHER MIDDLEWARE ****/
'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
];
} UsageAdd the following to your routes file: // 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 **/ Once this route group is added to the routes file, a user can access all locales added into
The package sets your application locale You may add middleware to your group like this: Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function(){ //...
}); Recommendations1.: It is strongly recommended to use a redirecting middleware.
Urls without locale should only be used to determine browser/default locale and to redirect to the localized url.
Otherwise, when search engine robots crawl for example 2.: It is strongly recommended to localize your links, even if you use a redirect middleware. Otherwise, you will cause at least one redirect each time a user clicks on a link. Also, any action url from a post form must be localized, to prevent that it gets redirected to a get request. Redirect MiddlewareThe following redirection middleware depends on the settings of LocaleSessionRedirectWhenever a locale is present in the url, it will be stored in the session by this middleware. In there is no locale present in the url, then this middleware will check the following
For example, if a user navigates to http://url-to-laravel/test and LocaleCookieRedirectSimilar to LocaleSessionRedirect, but it stores value in a cookie instead of a session. Whenever a locale is present in the url, it will be stored in the cookie by this middleware. In there is no locale present in the url, then this middleware will check the following
For example, if a user navigates to http://url-to-laravel/test and LaravelLocalizationRedirectFilterWhen the default locale is present in the url and For example, if HelpersThis package comes with a bunch of helpers. Localized URLsLocalized URLS taken into account route model binding when generating the localized route,
aswell as the Get localized URL // If current locale is Spanish, it returns `/es/test`
<a href="{{ LaravelLocalization::localizeUrl('/test') }}">@lang('Follow this link')</a> Get localized URL for an specific localeGet current URL in specific locale: // Returns current url with English locale.
{{ LaravelLocalization::getLocalizedURL('en') }} Get Clean routesReturns a URL clean of any localization. // Returns /about
{{ LaravelLocalization::getNonLocalizedURL('/es/about') }} Get URL for an specific translation keyReturns a route, localized to the desired locale. If the translation key does not exist in the locale given, this function will return false. // Returns /es/acerca
{{ LaravelLocalization::getURLFromRouteNameTranslated('es', 'routes.about') }} Get Supported LocalesReturn all supported locales and their properties as an array. {{ LaravelLocalization::getSupportedLocales() }} Get Supported Locales Custom OrderReturn all supported locales but in the order specified in the configuration file. You can use this function to print locales in the language selector. {{ LaravelLocalization::getLocalesOrder() }} Get Supported Locales KeysReturn an array with all the keys for the supported locales. {{ LaravelLocalization::getSupportedLanguagesKeys() }} Get Current LocaleReturn the key of the current locale. {{ LaravelLocalization::getCurrentLocale() }} Get Current Locale NameReturn current locale's name as string (English/Spanish/Arabic/ ..etc). {{ LaravelLocalization::getCurrentLocaleName() }} Get Current Locale Native NameReturn current locale's native name as string (English/Español/عربى/ ..etc). {{ LaravelLocalization::getCurrentLocaleNative() }} Get Current Locale DirectionReturn current locale's direction as string (ltr/rtl). {{ LaravelLocalization::getCurrentLocaleDirection() }} Get Current Locale ScriptReturn the ISO 15924 code for the current locale script as a string; "Latn", "Cyrl", "Arab", etc. {{ LaravelLocalization::getCurrentLocaleScript() }} Set view-base-path to current localeRegister the middleware Now you can wrap your views in language-based folders like the translation files.
Map your own custom lang url segmentsAs you can modify the supportedLocales even by renaming their keys, it is possible to use the string // config/laravellocalization.php
'localesMapping' => [
'en-GB' => 'uk'
], After that LaravelLocalization::getLocalizedURL('en-GB', 'a/b/c'); // http://url-to-laravel/uk/a/b/c
LaravelLocalization::getLocalizedURL('uk', 'a/b/c'); // http://url-to-laravel/uk/a/b/c Creating a language selectorIf you're supporting multiple locales in your project you will probably want to provide the users with a way to change language. Below is a simple example of blade template code you can use to create your own language selector. <ul>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<li>
<a rel="alternate" hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
{{ $properties['native'] }}
</a>
</li>
@endforeach
</ul> Here default language will be forced in getLocalizedURL() to be present in the URL even Note that Route Model Binding is supported. Translated RoutesYou may translate your routes. For example, http://url/en/about and http://url/es/acerca (acerca is about in spanish) or http://url/en/article/important-article and http://url/es/articulo/important-article (article is articulo in spanish) would be redirected to the same controller/view as follows: It is necessary that at least the For each language, add a <?php
// resources/lang/en/routes.php
return [
"about" => "about",
"article" => "article/{article}",
]; <?php
// resources/lang/es/routes.php
return [
"about" => "acerca",
"article" => "articulo/{article}",
]; You may add the routes in 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;
});
//,...
}); Once files are saved, you can access http://url/en/about , http://url/es/acerca , http://url/en/article/important-article and http://url/es/articulo/important-article without any problem. Translatable route parametersMaybe you noticed in the previous example the English slug in the Spanish url:
It is possible to have translated slugs, for example like this:
However, in order to do this, each article must have many slugs (one for each locale).
Its up to you how you want to implement this relation. The only requirement for translatable route parameters is, that the relevant model implements the interface Implementing LocalizedUrlRoutableTo implement Route Model BindingTo use route-model-binding, one should overwrite the function public function resolveRouteBinding($slug)
{
return static::findByLocalizedSlug($slug)->first() ?? abort(404);
} Tutorial VideoYou may want to checkout this video which demonstrates how one may set up translatable route parameters. EventsYou can capture the URL parameters during translation if you wish to translate them too. To do so, just create an event listener for the Event::listen('routes.translation', function($locale, $attributes)
{
// Do your magic
return $attributes;
}); Be sure to pass the locale and the attributes as parameters to the closure. You may also use Event Subscribers, see: http://laravel.com/docs/events#event-subscribers Caching routesTo cache your routes, use: php artisan route:trans:cache ... instead of the normal For the route caching solution to work, it is required to make a minor adjustment to your application route provision. In your App's <?php
class RouteServiceProvider extends ServiceProvider
{
use \Mcamara\LaravelLocalization\Traits\LoadsTranslatedCachedRoutes; For more details see here. Common IssuesPOST is not workingThis may happen if you do not localize your action route that is inside your For example, if you use
will not work. Instead, one has to use <form action="{{ \LaravelLocalization::localizeURL('/logout') }} " method="POST">
<button>Logout</button>
</form> Another way to solve this is to put http method to config to 'laravellocalization.httpMethodsIgnored' to prevent of processing this type of requests |