drehimself / laravel-language-switcher-example

http://usefullaravelpackages.com
12 stars 15 forks source link

[FIXED] Routing to custom routes with variables, and language manually modification on get request not managed #5

Open Techscq opened 2 years ago

Techscq commented 2 years ago

Hey bud great tutorial but this guide have two issue when it comes to real projects where u need create routes with special parameters u have to read the route parameters and merge it with the new language , example of this in Laravel 9 {{ route(Route::currentRouteName(), array_merge(Route::current()->parameters(),['language'=>'en'])) }} this will basically merge the current parameters with the new language parameter just replace the 'en' in this example for the language key u want, the second issue is that if a user manually edit the get route with a unknown Language the website will show the keyword used on ur translation var example "myproject/en/someroute" => "myproject/UNKNOWNLANGUAGE/someroute" so to fix this u should add a little logic to your middleware example =>

if($request->language == 'en' || $request->language == 'es' || $request->language == null){

        App::setLocale($request->language);

        return $next($request);

        }else{

            App::setLocale(app()->getLocale());

            return redirect()->to(route(Route::currentRouteName(), array_merge(Route::current()->parameters(),['language'=>app()->getLocale()])));

        }

so basically this will read ur request language and look for a valid app lang in my case i only work with Spanish and English traslations and u have to add also a null language condition in case the request doesnt send a explicit language then u return the request with the new language BUT if the condition doesnt meet ur app languages u have to set the default language by taking care of the special routes( routes that need custom variables) by custom variables i mean routes like

Route::get('/Dashboard/someroute/{somevar}', function () {
return view('dashboard');
});

i hope i made this clear for anyone needing help with this, its a very simple thing but some people may need some help, theres others way to make the same functionality middleware but this is how i have manage it and it have worked without any headache till now

Happy coding!