Skip to content

Instantly share code, notes, and snippets.

@Mevrael
Created January 24, 2016 13:39
Show Gist options
  • Save Mevrael/9a7d03e1dcaf5d3f6520 to your computer and use it in GitHub Desktop.
Save Mevrael/9a7d03e1dcaf5d3f6520 to your computer and use it in GitHub Desktop.
Example of Laravel localization provider
<?php // after locale
'additional_locales' => ['de'],
<?php
namespace App\Core;
class Application extends \Illuminate\Foundation\Application
{
public function getLocalePrefix($locale_to = null) {
if ($locale_to === null) {
$locale = self::getLocale();
} else {
$locale = $locale_to;
}
if ($locale === config('app.fallback_locale')) {
$lang_prefix = '';
} else {
$lang_prefix = $locale;
}
return $lang_prefix;
}
}
<?php
namespace App\Core;
use Illuminate\Support\Facades\App;
class UrlGenerator extends \Illuminate\Routing\UrlGenerator
{
/**
* Generate an absolute URL to the given path.
*
* @param string $path
* @param mixed $extra
* @param bool|null $secure
* @return string
*/
public function to($path, $extra = [], $secure = null)
{
$path = App::getLocalePrefix() . $path;
return parent::to($path, $extra, $secure);
}
}
<?php // new file
namespace App\Providers;
use App\Core\UrlGenerator;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\ServiceProvider;
class LocaleServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// detect user language and set app locale
if (in_array($s1 = Request::segment(1), config('app.additional_locales'))) {
// 1. set app locale if first URL segment is in additional locales
App::setLocale($s1);
} else if (Auth::check()) {
// 2. user logged in, set language from user profile settings
// TODO
} else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
// 3. detect lang from user agent
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (in_array($lang, config('app.additional_locales'))) {
App::setLocale($lang);
}
}
// 4. else Laravel automatically will use fallback_locale
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind('url', 'App\Core\UrlGenerator');
}
}
<?php // added global prefix
$router->group(['prefix' => App::getLocalePrefix(), 'namespace' => $this->namespace], function ($router) {
require app_path('Http/Routes/app_routes.php');
require app_path('Http/Routes/api_routes.php');
require app_path('Http/Routes/admin_routes.php');
require app_path('Http/Routes/dev_routes.php');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment