Detect Browser Language using PHP

Example (Middleware)

<?php

namespace App\Http\Middleware;

use Closure;
use App;
use Illuminate\Support\Facades\Cookie;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //$locale = App::getLocale();
        //logg($locale);
        $locale = $request->input('locale');
        //logg($locale);
        //logg(session()->get('locale'));
        if($locale != false){
            //session(['locale' => $locale]);
            $this->save_cookie($locale);
        }else{
            //if(session()->get('locale') != false){
            $cookie_locale = Cookie::get('locale');
            if($cookie_locale != false){
                App()->setLocale($cookie_locale);
            }else{
                //偵測browser語言
                $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
                if($lang == 'en'){
                    $this->save_cookie('en');
                }else{
                    $this->save_cookie('zh_TW');
                }
            }
        }

        return $next($request);
    }

    private function save_cookie($locale){
        $minutes = 60 * 24 * 365 * 1;// 1 year
        $cookie = Cookie::queue('locale', $locale, $minutes);
        App()->setLocale($locale);
    }
}

Reference:

  1. https://stackoverflow.com/questions/3770513/detect-browser-language-in-php