I encountred a problem when trying to prefixing my routes with new set locale. When I return app()->getLocale() from a controller or a route closure it returns new set locale correctly, but when I put it inside Route prefix I get the default one 'en'. In my case the new locale is 'ar'.
This is my code inside web.php
<?php
//Request to put the choosen locale into the session
Route::get('locale/{locale}', function($locale) {
session()->put('userLocale', $locale);
return redirect(app()->getLocale());
});
//Group of routes that are supposed to be prefixed with new set locale 'ar'
Route::group(['prefix' => app()->getLocale(), 'middleware' => 'locale'], function() {
Route::get('/', function() {
return app()->getLocale();
});
});
And this is the middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
class Locale
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->app->setLocale(session('userLocale'));
return $next($request);
}
}
Note the statement "app()->getLocale()" inside Route prefix, this statement's value always is "en". But when I return it from within the closure it prints the new set locale "ar".
What I'm trying to say is that, inside prefix, app()->getLocale()'s value is always "en", but inside the Closure its value is "ar".
So when I run "localehost:8000/locale/ar" in the browser the output is "ar" and that is correct but the url becomes "localehost:8000/en" and that should be "localehost:8000/ar" isn'it ? When I run "localehost:8000/ar" in the browser I get a 404 page.
I tried to set the prefix from within RouteServiceProvider's mapWebRoutes methode but It doesn't work because I think that the service provider is executed before the middlware so It can't recognize the new locale that is set by the middlware.
I hope to get help or another approach to prefix the routes with new locale because maybe I'm doing somthing wrong.