I am looking for a way to make all app route's have multiple locales without using route groups. This is because I use an external extensions package, which means routes are registered in many places.
Essentially I want to have /foo/bar as well as /en/foo/bar, /de/foor/bar, /es/foo/bar etc all to be recognised and processed by the /foot/bar route
Route::get('foo/bar', function () {
return App::getLocale() . ' result';
});
So the above would give me 'en result' or 'de result' or 'es result'.
I already have middleware that sets the locale based on the path segment. I have tried the following with no luck.
...
$newPath = str_replace($locale,'',$request->path());
$request->server->set('REQUEST_URI',$new_path);
}
return $next($request);
Hopefully this is possible, or there is some other way of achieving it.
EDIT------
Based on a comment below I quickly hacked it by adding the following code into public/index.php. Hopefully this will give a better idea of what i'm trying to achieve by editing the request object.
$application_url_segments = explode( '/', trim( $_SERVER["REQUEST_URI"], '/' ) );
$application_locale = $application_url_segments[0];
$application_locales = ['en' => 'English', 'de' => 'German'];
if ( array_key_exists( $application_locale, $application_locales ) ) {
$_SERVER["REQUEST_URI"] = str_replace( '/' . $application_locale,'',$_SERVER["REQUEST_URI"] );
}
Here is the correct code to edit the URL before the routes get called.
<?php namespace App\Providers;
use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;
class LanguageServiceProvider extends ServiceProvider {
public function register() {
Request::instance()->server->set('REQUEST_URI',"/uri/");
}
}
To note, fetching the path from the Request instance without duplicating it first will for some reason cause the REQUEST_URI to not be editable. I assume somewhere in the codebase laravel is initializing the request when you call the path() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With