duanhao1004 2017-08-17 15:26
浏览 46
已采纳

多语言网站,使用语言操作?

I use laravel 5.3 framework and have a middleware to check for languages, redirects are correct and localization works, my question is, it is recommended to save selected language in a cookie? So I will be able to redirect the user every time to the selected language? Can it be also good for performance...

At the moment if I call App::getLocale() is get the right language.

I'm generally interested to know is this way correct what I do?

  • 写回答

2条回答 默认 最新

  • douhui7136 2017-08-17 15:38
    关注

    I use this middleware to check/set the language in session for every request:

    <?php
    
    namespace App\Http\Middleware;
    
    use App;
    use Auth;
    use Config;
    use Session;
    use Closure;
    
    class SetLocale
    {
        public function handle($request, Closure $next)
        {
            // If the session doesn't have already a locale
            if (!Session::has('locale')) {
                // Set the logged in user language
                if (Auth::check() && Auth::user()->lang->code) {
                    Session::put('locale', Auth::user()->lang->code);
                } else {
                    // Else get the http header language and set it
                    $requestLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
                    if (App\Lang::where('code', $requestLanguage)->exists()) {
                        Session::put('locale', $requestLanguage);
                    } else {
                        // If none of the above worked use the app deafult language
                        Session::put('locale', Config::get('app.locale'));
                    }
                }
            }
            // Set the output locale as app locale
            App::setLocale(Session::get('locale'));
    
            return $next($request);
        }
    }
    

    Hope this helps you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程