Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.0.* middleware to remove prefix locale from url before routes are processed

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"] );

}
like image 594
Ben Avatar asked Sep 25 '22 15:09

Ben


1 Answers

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.

like image 152
Tom C Avatar answered Oct 11 '22 13:10

Tom C