この記事のおかげで、多言語サイト実現のための言語切り替えをどうやって仕込もうかと悩んでいたのが一気に解決した。ありがたや。
Laravel 5 And His F*cking non-persistent App SetLocale
http://mydnic.be/post/laravel-5-and-his-fcking-non-persistent-app-setlocale
1 |
$ php artisan make:controller LanguageController |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Http\Requests; use Config; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; class LanguageController extends Controller { public function switchLang($lang) { if (array_key_exists($lang, Config::get('languages'))) { Session::set('applocale', $lang); } return Redirect::back(); } } |
config/languages.php
1 2 3 4 |
return [ 'en' => 'English', 'fr' => 'Français', ]; |
routes.php
1 |
Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']); |
front-end
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> {{ Config::get('languages')[App::getLocale()] }} </a> <ul class="dropdown-menu"> @foreach (Config::get('languages') as $lang => $language) @if ($lang != App::getLocale()) <li> <a href="{{ route('lang.switch', $lang) }}">{{$language}}</a> </li> @endif @endforeach </ul> </li> |
app/Http/Middleware/Language.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
namespace App\Http\Middleware; use Closure; use Illuminate\Foundation\Application; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Session; class Language { public function handle($request, Closure $next) { if (Session::has('applocale') AND array_key_exists(Session::get('applocale'), Config::get('languages'))) { App::setLocale(Session::get('applocale')); } else { // This is optional as Laravel will automatically set the fallback language if there is none specified App::setLocale(Config::get('app.fallback_locale')); } return $next($request); } } |
Kernel.php
1 2 3 4 5 6 7 8 9 10 11 12 |
protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \App\Http\Middleware\Language::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], // ... ]; |