2016-12-09 8 views
0

私はlaravelにapiを持っており、ユーザーの言語で返された検証エラーが欲しいです。どうすればlaravel apiで言語を指定できますか?例えば、 は次のように応答します。検証エラーのためにlaravel 5.1 apiでどのように言語を検出できますか?

if ($validator->fails()) { 
      return response()->json([ 
       'errors' => $validator->getMessageBag()->getMessages(), 
      ], 400); 
     } 

各言語に最適です。 faとen。このためミドルウェア にミドルウェアを登録する)

<?php 
namespace App\Http\Middleware; 
use Closure; 
use Illuminate\Foundation\Application; 

/** 
* Class Localization 
* 
* @author Mahmoud Zalt <[email protected]> 
*/ 
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; 
    } 
} 

2:

答えて

1

1)アプリケーション/ HTTP /ミドルウェア

localization.php

にミドルウェアを作成し、その中にこれらを書きます。アプリの\のHttp \ Kernel.php に行くカーネルファイルであることをこの配列に追加します。

protected $middleware = [] 

この1つは。

\App\Http\Middleware\Localization::class, 

3)設定ディレクトリ内app.phpに

'supported_languagesを' => [ 'EN' => '英語'、 'FA' => 'ペルシャ']、これを追加

4)あなたの言語のlangフォルダ "resources/lang"に言語フォルダを作成します(この場合は[en]の隣にあります)。この質問のためには、あなたのfaフォルダにvalidation.phpファイルをコピーし、エラーテキストを変更してください。

5)リクエストのヘッダー "Content-Language"を([en]または[fa])に設定します。

1

これを行う必要はありません あなたのリソースでこれを行うことができます。フォルダ 1)Laravelのローカリゼーション機能を使用すると、さまざまな言語の文字列を簡単に検索でき、アプリケーション内で複数の言語を簡単にサポートできます。言語文字列は、resources/langディレクトリ内のファイルに格納されます。このディレクトリ内には、アプリケーションでサポートされている各言語のサブディレクトリがあります。 ステップバイステップガイドでは、次のリンクを確認してください。https://laravel.com/docs/5.3/localization

関連する問題