Aipo
Aipo

Reputation: 1985

Laravel language switcher, routes setup

I want to use routes example.com/en/item fon english, then call example.com/no/item my current controller:

class LocalizationController extends Controller
{
    public function switch($locale)
    {
        App::setLocale($locale);
        session(['locale'=> $locale]);
        return redirect()->back();
    }
}

web.php:

Route::group(['prefix' => app()->getLocale()], function () {
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/threads', 'ThreadsController@index');
});
Route::get('/lang/{locale}','LocalizationController@switch');

How to keep locale showing in url?

Upvotes: 0

Views: 347

Answers (1)

Patryk
Patryk

Reputation: 75

    return redirect(url()->previous()."?".http_build_query(['locale'=>$locale]));

or

    return redirect()->route('home', ['locale' => $locale]);

but in second example you must create name for your route, example:

Route::get('/lang/{locale}','PagesController@switch')->name('locale');

You will get something like this in your url:

http://192.168.1.49/test/public/home?locale=en

Update:

Inside your .env set =>

APP_URL=en 

Inside app\Providers\AppServiceProvider.php

set this

   \URL::forceRootUrl(\Config::get('app.url'));
    if (\Str::contains(\Config::get('app.url'), 'https://')) {
        \URL::forceScheme('https');
    }

That after go to home page you will have in url

http://192.168.1.49/test/public/home/en

Upvotes: 1

Related Questions