Hello,
How to create a multi-language site in Laravel 5.2:
config/app.php
'locale' => 'ca',
'locales' => ['ca' => 'Català', 'es' => 'Español', 'en' => 'English'],
app/Http/routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', [
'as' => 'underconstruction', 'uses' => 'Underconstruction\UnderconstructionController@showIndex'
]);
Route::get('/lang/{langcode?}', function ($langcode = 'ca') {
return redirect()->route('underconstruction');
});
});
app/Http/Kernel.php
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\LangMiddleware::class,
],
'api' => [
'throttle:60,1',
],
];
/app/Http/Middleware/LangMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use App;
class LangMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$lang = $request->segment(1);
$locale = $request->segment(2);
if ($lang == 'lang' && array_key_exists($locale, app()->config->get('app.locales'))) {
$request->session()->put('locale', $locale);
} else if ($request->session()->has('locale')) {
App::setLocale($request->session()->get('locale'));
}
return $next($request);
}
}
/app/Http/Controllers/Underconstruction/UnderconstructionController.php
<?php
namespace App\Http\Controllers\Underconstruction;
use App\Http\Controllers\Controller as Controller;
class UnderconstructionController extends Controller
{
public function showIndex() {
return app()->getLocale();
}
}
If you access to http://yourweb/ --> lang = ca
if you access to http://yourweb/lang/es --> lang = es
If you access to http://yourweb/ --> lang =es
Lang is saved in session data.
Best regards,
Iban Cardona.
No comments:
Post a Comment