Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Created September 3, 2018 14:07
Show Gist options
  • Save ricardocanelas/08bec2e801226af4fe8e3180a8de466d to your computer and use it in GitHub Desktop.
Save ricardocanelas/08bec2e801226af4fe8e3180a8de466d to your computer and use it in GitHub Desktop.
Laravel / Locale (middleware)
<?php // app/Http/kernel.php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
//...
protected $middlewareGroups = [
'web' => [
// ...
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\Locale::class, // <-- THE LOCALE MIDDLEWARE IS AFTER 'START-SESSION'
// ...
]
];
//...
}
<?php // config/languages.php
return [
'en' => 'English',
'pt' => 'Portuguese',
];
<?php // app/Http/Middleware/Locale.php
namespace App\Http\Middleware;
use Closure;
use Session;
use Config;
use App;
class Locale
{
public function handle($request, Closure $next)
{
$language = Session::get('language', Config::get('app.locale'));
$language = array_key_exists($language, Config::get('languages')) ? $language : Config::get('app.fallback_locale');
App::setLocale($language);
return $next($request);
}
}
<?php // resources/views/layouts/site.php
<form id='locale-form' method='post' action="{{ route('site.language')}}">
{{ csrf_field() }}
<input type='hidden' id='language_field' name='locale' value='{{ App::getLocale() }}'/>
</form>
<button id='pt' type='button'>PT</button>
<button id='en' type='button'>EN</button>
<script>
document.addEventListener("DOMContentLoaded", function ()
{
$pt = document.querySelector('button#pt');
$en = document.querySelector('button#en');
$pt.addEventListener('click', function (e) {
document.querySelector('#locale-form #language_field').value = 'pt'
document.querySelector('#locale-form').submit();
})
$en.addEventListener('click', function (e) {
document.querySelector('#locale-form #language_field').value = 'en'
document.querySelector('#locale-form').submit();
})
})
</script>
<?php // app/Http/Controllers/SiteController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function language(Request $request)
{
\Session::put('language', $request->get('locale', 'en'));
\App::setLocale($request->get('locale', 'pt'));
return \Redirect::back();
}
}
<?php // routes/web.php
Route::post('/language', 'SiteController@language')->name('site.language');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment