Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Magalliu's avatar

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?

0 likes
19 replies
Magalliu's avatar

I tried achieving that using Route:: helper but the problem is on the pages that have parameters.

<a class="dropdown-item" href="{{ route(Route::currentRouteName(), 'en') }}">

But it throws this error:

Missing required parameters for [Route: frontend.category] [URI: {locale}/{slug}]. (View: /var/www/html/project/resources/views/frontend/layouts/header.blade.php).

I cannot put parameters since the language switcher is on header and the parameters are different and many...

Any help would be appreciated!

khaledw62's avatar
Level 6

i almost understand you issue but let me know of i'm wrong, I did it in the blade view as following

    <?php
        $thisUrl = url()->current().'/';
        if (app()->getlocale() == 'en') {
            $newUrl  = str_replace('/en/', '/it/', $thisUrl);
        }else{
            $newUrl  = str_replace('/it/', '/en/', $thisUrl);
        }
     ?>

if you are just using two langs you may share 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);
    }
}

then in your Blade View

<a class="dropdown-item" href="{{ $newUrl }}">
2 likes
Magalliu's avatar

Sorry for the late response @khaledw62 but once we get off the office we cannot access remotely our projects from home.

Let me give a try and I will tell you.

Magalliu's avatar

Brother thank you very much because that worked for me. That is a very simple and good solution to my problem. May God bless you!

I'm sure that many will benefit from your answer about redirecting back with locale because in 3 days no one could give me correct answer in several forums.

Again, thank you!

sr57's avatar

You are welcome, your title gave me an example for one of my post yesterday ...

1 like
Magalliu's avatar

No in fact, your title gave me the example... I saw it at your post and the credentials for that goes to you... Thanks again and Happy Coding!

1 like
sr57's avatar

I didn't know I was so innovative. :-)

1 like
Magalliu's avatar

@khaledw62 I have another question related to my question even that the problem is already solved.

In case that in future I add other language like de and others languages as well, how can I manage it in that case.

Magalliu's avatar

Thanks for the suggestion @michaloravec , I know about mcamara package but the problem is that I have already completed the project and that was the last bug to fix. And I don't know how it will affect the project starting over with localization using mcamara package...

khaledw62's avatar

if you want a work around but it will be handy,

        $thisUrl = url()->current().'/';
        $appLocale = app()->getlocale();
        
        //Lets Say You Have Array of Languages
        $langs = ['en','it','de','es'];
        
        //Remove the current Language Url
        unset($langs[$appLocale]);
        //Generating Urls For All of Your Languages
        $urls = [];
        foreach ($langs as $lang) {
            $urls[$langs] = str_replace('/' . $appLocale . '/', '/' . $lang . '/', $thisUrl);
        }
1 like
Magalliu's avatar

Thanks again @khaledw62.

Look I was testing and in first place all seems good but there is a problem with AppServiceProvider solution and I can't understand why.

$thisUrl = url()->current().'/';
        if (app()->getlocale() == 'en') {
            $newUrl  = str_replace('/en/', '/it/', $thisUrl);
        } else {
            $newUrl  = str_replace('/it/', '/en/', $thisUrl);
       }

View::share('newUrl', $newUrl);

When I change first from /it/ to /en/ there are no problems. But when I try to change it from actual /en/ to /it/ it will redirect back to same page but with no locale changed. I've tested with dd the $newUrl variable and the print is correct and the locale is changed every time I change it. But it is not working on <a> tag.

This is how my blade looks like:

<div class="dropdown-menu" aria-labelledby="languageDropdown">
          @if ( Config::get('app.locale') == 'it')
          <a class="dropdown-item" href="{{ $newUrl }}">
            <span class="lang lang-en">English</span>
          </a>
          @elseif ( Config::get('app.locale') == 'en' )
          <a class="dropdown-item" href="{{ $newUrl }}">
            <span class="lang lang-it">Italian</span>
          </a>
          @endif
</div>

Maybe I'm doing something wrong in blade but my mind is really blocked now.

Magalliu's avatar

@khaledw62 and I have to specify that if I use the blade solution will work just fine. If I use AppServiceProvider solution will give me this problem so the locale will be changed only from it to en but not the other way around.

khaledw62's avatar

You May use a foreach instead of if

        //Lets Say You Have Array of Languages
        $langs = ['en' => ['label' => 'English','url' => '']];

        //Remove the current Language Url
        unset($langs[$appLocale]);
        //Generating Urls For All of Your Languages
        foreach ($langs as $lang => $labels) {
            $langs[$lang]['url'] = str_replace('/' . $appLocale . '/', '/' . $lang . '/', $thisUrl);
        }

and in your view

@foreach($langs as $code => $labels)
    <a class="dropdown-item" href="{{ $labels['url'] }}">
        <span class="lang lang-{{ $code }}">{{ $labels['label'] }}</span>
    </a>
    @endforeach
1 like
Magalliu's avatar

It will work for all array $langs elements but for it' language will not work.

        $thisUrl = url()->current().'/';
        $appLocale = app()->getLocale();


        //Lets Say You Have Array of Languages
        $langs = [
            'en' => ['label' => 'English','url' => ''],
            'it' => ['label' => 'Italian','url' => ''],
            'de' => ['label' => 'German','url' => '']
        ];

        //Remove the current Language Url
        unset($langs[$appLocale]);
        //Generating Urls For All of Your Languages
        foreach ($langs as $lang => $labels) {
            $langs[$lang]['url'] = str_replace('/' . $appLocale . '/', '/' . $lang . '/', $thisUrl);
        }

        View::share('langs', $langs);

Blade:

         @foreach($langs as $code => $labels)
          <a class="dropdown-item" href="{{ $labels['url'] }}">
              <span class="lang lang-{{ $code }}">{{ $labels['label'] }}</span>
          </a>
          @endforeach

It will show en and de but not it. Strange...

I want to specify that my default and fallback_locale are it.

levitorres's avatar

Thank you guys.I am just new on this website and I am glad I found this as you got every solutions I need. I couldnt ask for a better community.

1 like

Please or to participate in this conversation.