Skip to content

Instantly share code, notes, and snippets.

@rama-adi
Last active October 6, 2020 16:33
Show Gist options
  • Save rama-adi/ffc6c5c8cc567e86cc8d0c6cc2a6183c to your computer and use it in GitHub Desktop.
Save rama-adi/ffc6c5c8cc567e86cc8d0c6cc2a6183c to your computer and use it in GitHub Desktop.
Contoh Localization di Laravel
  1. Add di routes/web.php
Route::get('locale/{locale}', [localeController::class, 'change']);
  1. 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('/');
        }
    }
}
  1. 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);
    }
}
  1. Register di Kernel.php $middlewareGroups paling bawah
// Jangan lupa import SetLocale dulu
// use App\Http\Middleware\SetLocale;
SetLocale::class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment