创建一个支持本地化的API

青青子衿,悠悠我心。但为君故,沉吟至今。
  • create a middleware

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    use Closure;
    use Illuminate\Foundation\Application;

    /**
    * Class Localization
    *
    * @author Mahmoud Zalt <mahmoud@zalt.me>
    */
    class Localization
    {

    /**
    * Localization constructor.
    *
    * @param \Illuminate\Foundation\Application $app
    */
    public function __construct(Application $app)
    {
    $this->app = $app;
    }

    /**
    * Handle an incoming request.
    *
    * @param \Illuminate\Http\Request $request
    * @param \Closure $next
    *
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
    // read the language from the request header
    $locale = $request->header('Content-Language');

    // if the header is missed
    if(!$locale){
    // take the default local language
    $locale = $this->app->config->get('app.locale');
    }

    // check the languages defined is supported
    if (!array_key_exists($locale, $this->app->config->get('app.supported_languages'))) {
    // respond with error
    return abort(403, 'Language not supported.');
    }

    // set the local language
    $this->app->setLocale($locale);

    // get the response after the request is done
    $response = $next($request);

    // set Content Languages header in the response
    $response->headers->set('Content-Language', $locale);

    // return the response
    return $response;
    }
    }

  • Register the middleware in the Middlewares

  • add this to the app.php config file

    1
    'supported_languages' => ['en' => 'English', 'ru' => 'Russian'],
  • create language folder in the lang folder “resources/lang” for your language (in this case it is [ru] next to [en]) and of course set your files there.

  • create sample route to test this: {you need to use the trans function}

    1
    2
    3
    4
    5
    Route::get('welcome', function () {

    echo trans('messages.welcome');

    });
  • call the endpoint “http://api.xxxxx.dev/welcome/“ and set the header “Content-Language” in your request to ([en] or [ru]).

https://laravel-tricks.com/tricks/create-api-that-supports-localization