Skip to content

Instantly share code, notes, and snippets.

@pedrosancao
Last active June 12, 2019 12:48
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 pedrosancao/375dbb55d3f2278ced616b08d7836dc1 to your computer and use it in GitHub Desktop.
Save pedrosancao/375dbb55d3f2278ced616b08d7836dc1 to your computer and use it in GitHub Desktop.
Laravel localized URLs - POC for package
<?php
protected $routeMiddleware = [
//...
'locale' => \APP\Http\Middleware\LocaleRedirect::class,
//...
];
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class LocaleRedirect
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$currentRoute = $request->route()->getName();
$defaultLocale = config('app.locale');
$currentLocale = \Session::get('locale', app()->getLocale());
$matches = [];
if (preg_match('/^([a-z]{2}(?:-[A-Z{2}])?)\.(.+)/', $currentRoute, $matches) === 0) {
$matches = [
1 => $defaultLocale,
2 => $currentRoute,
];
}
if ($matches[1] != $currentLocale) {
$routeName = ($currentLocale === $defaultLocale ? '' : ($currentLocale . '.')) . $matches[2];
if (\Route::has($routeName)) {
dd(route($routeName));
return redirect()->route($routeName);
}
}
return $next($request);
}
}
<?php
Route::get('idioma/{locale}', function($locale) {
\Session::put('locale', $locale);
return redirect()->route('site.home');
})
->where('locale', join('|', array_keys(config('app.locales'))))
->name('change-lang');
Route::group(['middleware' => 'locale'], function () {
Route::get('inicio', 'PageController@home')->name('site.home');
Route::get('home', 'PageController@home')->name('en.site.home');
Route::get('quem-somos', 'PageController@about')->name('site.about');
Route::get('about', 'PageController@about')->name('en.site.about');
Route::get('produtos', 'PageController@products')->name('site.products');
Route::get('products', 'PageController@products')->name('en.site.products');
Route::any('contato', 'PageController@contact')->name('site.contact');
Route::any('contact', 'PageController@contact')->name('en.site.contact');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment