Skip to content

Instantly share code, notes, and snippets.

@stasyanko
Created May 3, 2018 09:04
Show Gist options
  • Save stasyanko/243963938d364a518713d8f65dff1b94 to your computer and use it in GitHub Desktop.
Save stasyanko/243963938d364a518713d8f65dff1b94 to your computer and use it in GitHub Desktop.
Laravel: optional language route prefix (e.g. domain.com/fr/about or without prefix domain.com/about)
// include any routes you need here that are accessed with GET method
// as POST routes don't need prefixing usually
Route::get('/', 'HomeController@index');
Route::get('/about', 'HomeController@showAbout');
<?php
// custom loc_url helpers for using in blade template
if (! function_exists('loc_url')) {
/**
* Return URL with lang prefix to slug
*/
function loc_url($slug)
{
$locale = app()->getLocale();
if($slug === '/') {
return $locale === 'en' ? secure_url('/') : secure_url($locale);
}
// if there is no language prefix, return url without prefix
return $locale === 'en' ? secure_url($slug) : secure_url($locale . '/' . $slug);
}
}
<?php
// Locale.php middleware
namespace App\Http\Middleware;
use Closure;
class Locale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->method() === 'GET') {
$locale = config('app.locale');
$segment = $request->segment(1);
if (in_array($segment, config('app.locales'))) {
$locale = $segment;
}
session(['locale' => $locale]);
app()->setLocale($locale);
}
return $next($request);
}
}
// a group with empty prefix
Route::group([
'middleware' => 'locale',
], function() {
require base_path().'/routes/GetRoutes.php';
});
// a group with lang prefix
Route::group([
'prefix' => '{lang?}',
'middleware' => 'locale',
], function() {
require base_path().'/routes/GetRoutes.php';
});
@stasyanko
Copy link
Author

I had problems placing optional route prefix in my Laravel app. I found this solution and decided to share that.

@BenjaminHoegh
Copy link

where are the files located?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment