根据浏览器语言和用户表值设置语言环境

时间:2019-03-11 14:53:05

标签: laravel

我正在尝试使用Laravel进行一些语言选择。

我有一个可行的解决方案,用户可以在其中更改语言:

Http / Middleware / Localization.php:

<?php

namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ( \Session::has('locale')) {
            \App::setLocale(\Session::get('locale'));

            // You also can set the Carbon locale
            Carbon::setLocale(\Session::get('locale'));
        }   

        return $next($request);
    }
}

链接:

<li><a href='locale/da'>Danish</a></li>
<li><a href='locale/en'>English</a></li>

此解决方案运行良好。但是,如果用户未登录,我想检查用户浏览器的语言,如果用户已登录,请在用户表字段“ lang”中检查语言。

我认为解决方案应如下所示: (我已经直接在视图中实现了这一点。)

不确定是否应在设置了语言环境的config / app.php中实现它。

'locale'=>'en',

  @php
    // If user is logged in
    if (Auth::check())
    {
        // Get the user specific language
        $locale = Auth::user()->lang;

        // Set the language
        App::setLocale($locale);
    }
    else {

        $locale = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

        if (!empty($locale)) {
            $locale == "en";
        }

        if ( \Session::has('locale')) {           
        } else{
            App::setLocale($locale);
        }
    }
@endphp

0 个答案:

没有答案
相关问题