- Add di
routes/web.php
Route::get('locale/{locale}', [localeController::class, 'change']);
App\Http\Controllers\LocaleController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Session;
class localeController extends Controller
{
public function change($locale)
{
// in_array utk cek apakah locale nya ada gak. silahkan tambah mau support bahasa apa aja
if (in_array($locale, ['en', 'id'])) {
Session::put('locale', $locale);
return redirect()->back();
} else {
// redirect kalo ga ada
return redirect('/');
}
}
}
- Middleware
SetLocale.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Session::has('locale')) {
$lang = Session::get('locale');
App::setLocale($lang);
} else {
Session::put('locale', 'id');
}
return $next($request);
}
}
- Register di
Kernel.php
$middlewareGroups
paling bawah
// Jangan lupa import SetLocale dulu
// use App\Http\Middleware\SetLocale;
SetLocale::class