Skip to content

Instantly share code, notes, and snippets.

@soipo

soipo/Locale.php

Last active Mar 15, 2019
Embed
What would you like to do?
Laravel 5 session locale and api middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
class Locale {
const SESSION_KEY = 'locale';
public function handle(Request $request, Closure $next) {
$fallbackLocale = config('translatable.fallback_locale');
$locales = array_keys(config('translatable.locales'));
$headerLocale = $request->header('Content-Language');
$session = $request->getSession();
if(!is_null($headerLocale) && in_array($headerLocale, $locales)){
$locale = $headerLocale;
}else if($request->has('lang') && in_array($request->get('lang'), $locales)) {
$locale = $request->get('lang');
}else if($session && $session->has(self::SESSION_KEY) && in_array($session->get(self::SESSION_KEY), $locales)){
$locale = $session->get(self::SESSION_KEY);
}else{
$locale = $fallbackLocale;
}
if($locale){
if($session){
$session->put(self::SESSION_KEY, $locale);
}
app()->setLocale($locale);
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.