본문 바로가기

개발/Laravel

Laravel 현지화 URL Prefix 미들웨어 처리

1. app\Http\Middleware\SetLocale.php 미들웨어 생성

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */

    protected $languages = ['en','ko','ja','zh'];

    public function handle($request, Closure $next)
    {
        $locale = $request->segment(1);

        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        } else {
            App::setLocale($locale);
            session()->put('locale', $request->lang);
        }

        return $next($request);
    }
}

2. app\Http\Kernel에 미들웨어 등록

protected $routeMiddleware = [
        ...
        'locale' => \App\Http\Middleware\SetLocale::class,
    ];

3. routes\web.php에 다국어 처리 routes 연결

Route::group(['prefix' => '/{locale}', 'middleware' => 'locale'], function ($locale) {
    Route::get('/globalpage', [GlobalController::class, 'globalPage']);
});
반응형