如何检测laravel 5.1 api中的语言验证错误?

时间:2016-12-09 12:04:57

标签: laravel api laravel-5.1

我在laravel中有一个api,我希望用户的语言返回验证错误。如何在laravel api中指定语言? 例如回复:

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

最适合每种语言。 fa和en。

2 个答案:

答案 0 :(得分:1)

1)在App / Http / Middleware中创建中间件

localization.php

并在其中写下:

<?php
namespace App\Http\Middleware;
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;
    }
}

2)在中间件中注册中间件 为了这。转到App \ Http \ Kernel.php 在内核文件中添加此数组:

 protected $middleware = []

这一个。

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

3)将其添加到config dir

中的app.php

&#39; supported_languages&#39; =&GT; [&#39;恩&#39; =&GT; &#39;英语&#39;,&#39; fa&#39; =&GT; &#39;波斯&#39],

4)在lang文件夹中创建语言文件夹&#34; resources / lang&#34;对于你的语言(在这种情况下它是[en]旁边的[fa]),当然还有你的文件。对于此问题,只将validation.php文件复制到fa文件夹并更改错误文本。

5)设置标题&#34; Content-Language&#34;在你的请求中[(en]或[fa])。

答案 1 :(得分:1)

没有必要做这一切 您可以在资源文件夹中执行此操作 1)Laravel的本地化功能提供了一种检索各种语言字符串的便捷方式,使您可以轻松地在应用程序中支持多种语言。语言字符串存储在resources / lang目录中的文件中。在此目录中,应用程序支持的每种语言都应该有一个子目录 有关分步指南,请查看以下链接:https://laravel.com/docs/5.3/localization

相关问题