Skip to content

Instantly share code, notes, and snippets.

@irfanm96
Created November 16, 2019 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irfanm96/bef135c923929a5dbb696042a642ab5c to your computer and use it in GitHub Desktop.
Save irfanm96/bef135c923929a5dbb696042a642ab5c to your computer and use it in GitHub Desktop.
Laravel Localization,Middleware to set locale based on route
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$locale = 'en'; // set en as the fallback locale
if ($request->is('/es/*')) { // if the route starts with /es/* set locale to ES
$locale = 'es';
} else if ($request->is('/fr/*')) { // if the route starts with /fr/* set locale to FR
$locale = 'fr';
}
//set the derived 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