Browser Language Detection

PHP (Laravel):

    public function __construct(){
        //parent::__construct();

        $this->middleware(function ($request, $next) {
            $locale = $request->input('locale');
            if($locale != false){
                $lang_data = Language::where('code', $locale)->first();
                if($lang_data == false){
                    $locale = $this->locale;
                }
                //Set cookie only when locale has value
                setcookie('locale', $locale, time() + 30*24*60*60);
                App()->setLocale($locale);
            }else{
                $locale = val($_COOKIE, 'locale');
                if($locale != false){
                    App()->setLocale($locale);
                }
            }

            return $next($request);
        });

        //Following lines will be excuted before $this->middleware()
        $this->locale = App()->getLocale();
        //setcookie('locale', $this->locale, time() + 30*24*60*60);
        //logg($this->locale);
    }

Javascript:

        $(document).ready(function(){
            var lang = Cookies.get('locale');
            if(typeof lang == 'undefined' || lang == null){
                lang = browser_lang();
                Cookies.set('lang', lang, { expires: 30 });
                go_lang(lang);
            }
        });
        

        function browser_lang(){
            var lang = navigator.language || navigator.userLanguage;

            if(lang.match(/.*zh.*/i) != null){
                return 'zhtw';
            }else if(lang.match(/.*de.*/i) != null){
                return 'de';
            }else{
                return 'en';
            }
        }

        function go_lang(code){
            window.location.href = '/?locale=' + code;
        }

jscookie plugin:

https://github.com/js-cookie/js-cookie