Hi,
a while ago i developed a multilingual platform for a client and used the following way to implement any number of languages needed:
Routes file:
// German
Route::get('/musikfilter', 'ProductController@filter')->name('de.products.filter');
// English
Route::group(['prefix' => 'en'], function () {
Route::get('/musicfilter', 'ProductController@filter')->name('en.products.filter');
});
To avoid conflicting named routes i prefix them with an abbreviation of the name of the language.
Next we need to find a way to make working with named routes simple again.
For that i implemented a new function "localizeRoute" and saved it in "app\Http\Helper\LocaleHelper.php"
/*
* Used to localize a route based on what locale the application is running in.
*/
function localizeRoute($name, $locale = '') {
return (empty($locale) ? App::getLocale().'.'.$name : $locale.'.'.$name);
}
To make that function available in every part of your application you need to register it. I did so in the "register"-method of "AppServiceProvider.php"
/**
* Register any application services.
*
* @return void
*/
public function register()
{
require_once base_path('app/Http/Helpers/LocaleHelper.php');
// ...
}
Now we can use it very easily in every part of our application. Some examples:
// In controllers
return redirect()->route(localizeRoute('users.index'));
// In views
<a href="{{ route(localizeRoute('users.edit'), $user->id) }}"><i class="fa fa-edit fa-lg" aria-hidden="true"></i></a>
Finally we need to solve the problem of changing the applications locale based on the url. I wrote a middleware "LocaleMiddleware" for that
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
use Carbon\Carbon;
class LocaleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
/*
* We read the first segment of an URL (e.g. /en) and set it as the applications locale,
* if it's part of the allowed locales. Otherwise the fallback locale is used.
*/
$locale = (in_array(request()->segment(1), config('app.locales')) ? request()->segment(1) : config('app.fallback_locale'));
App::setLocale($locale);
Carbon::setLocale($locale);
return $next($request);
}
}
Don't forget to include it in "App\Http\Kernel.php"
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\LocaleMiddleware::class,
\App\Http\Middleware\RedirectMiddleware::class,
];
Hope that helps!