How to detect language preference in Laravel 5

Or you can use Illuminate\Http\Request::getPreferredLanguage

Like this, in middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;

class Locale {

  const SESSION_KEY = 'locale';
  const LOCALES = ['en', 'cs'];

  public function handle(Request $request, Closure $next) {
    /** @var Session $session */
    $session = $request->getSession();

    if (!$session->has(self::SESSION_KEY)) {
      $session->put(self::SESSION_KEY, $request->getPreferredLanguage(self::LOCALES));
    }

    if ($request->has('lang')) {
      $lang = $request->get('lang');
      if (in_array($lang, self::LOCALES)) {
        $session->put(self::SESSION_KEY, $lang);
      }
    }

    app()->setLocale($session->get(self::SESSION_KEY));

    return $next($request);
  }
}

I just made a Middleware for this, it may be useful.

First you set $availableLangs the array of the available languages in your app, you may use config\app.php instead of initializing the array in the middleware as I did.

If the first language is available in the request language data, it sets the locale, if not, it will search the next one, and so on.

class GetRequestLanguage
{

    public function handle($request, Closure $next)
    {
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        } else {
            $availableLangs = ['pt', 'en'];
            $userLangs = preg_split('/,|;/', $request->server('HTTP_ACCEPT_LANGUAGE'));

            foreach ($availableLangs as $lang) {
                if(in_array($lang, $userLangs)) {
                    App::setLocale($lang);
                    Session::push('locale', $lang);
                    break;
                }
            }
        }

        return $next($request);
    }
}

To simply get the locale from the header, you can grab the http-accept-language value from the request. This is accessible via a facade or you can use the request variable in your middleware:

Request::server('HTTP_ACCEPT_LANGUAGE')

// OR

$request->server('HTTP_ACCEPT_LANGUAGE');

This returns a string which looks like this: en-GB,en;q=0.8. You can then parse it (perhaps using explode()?) and grab the language from there.

However, this sort of thing can sometimes get complicated. If you need to do something more advanced, there's a package which can do all of this for you:

https://github.com/mcamara/laravel-localization