Search code examples
laravelhttp-redirectlocalizationlocalemultilingual

Laravel Redirect back to same page after changing locale


The way I implemented multilang is through middleware and routes.

Middleware Localization.php looks like this:

public function handle(Request $request, Closure $next)
{
    $locale = $request->segment(1); 


    if(empty($locale)) { 
        return redirect()->to('/' . app()->getLocale());
    }

    if(in_array($locale, ['en','it'])) {
        App::setLocale($locale);
        $request->except(0); 
    }

    return $next($request);
}

And in my web.php I have:

Route::get('locale/{locale}', function ($locale){

  \Session::put('locale', $locale);
  $path = Route::getCurrentRoute()->getPath();

  return redirect($path);

})->name('langroute');

In blade I'm using it like this:

<a class="dropdown-item" href="{{ url('/en') }}">

How can I redirect back to same page after changing to another lang?


Solution

  • Sharing a global variable to all of your views as following in your AppServiceProvider:

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Facades\View;
    use Illuminate\Support\ServiceProvider;
    
    class AppServiceProvider extends ServiceProvider
    {
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
    
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $thisUrl = url()->current().'/';
        if (app()->getlocale() == 'en') {
            $newUrl  = str_replace('/en/', '/it/', $thisUrl);
        }else{
            $newUrl  = str_replace('/it/', '/en/', $thisUrl);
        }
        View::share('newUrl', $newUrl);
    }
    }
    

    And you can redirect in blade same like before:

    <a class="dropdown-item" href="{{ $newUrl }}">