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

Cryank's avatar

Issue in usage of URL::previous() and switch lang

hello everyone,
I have a back button which looks

<a class="btn btn-default pull-right" href="{{URL::previous()}}">

This will go back go previous page on click, however it falls to "infinity loop" after switching language.

here is my routes for switch

Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);

In my LangController

 public function switchLang($lang)
    {
        if (array_key_exists($lang, Config::get('languages'))) {
            Session::set('applocale', $lang);
        }
        return Redirect::back();
    }

In my case,
At the beginning, says current page is "/post" , when I click create button I've been "/post/create". At this time, the back button in create page works fine, the link of URL::previous() would be "/post". However, when I switch lang at create page, it went to /lang/{lang} and then redirect back. Therefore the back button of create page after switching language is broken with URL::previous() "/post/create"

Hope you guys understand what I said :S
Thanks a lot

0 likes
6 replies
bobbybouwmann's avatar

Yeah I understand. In that case the back button is not useful. Why don't you redirect the user back to the "/post" page instead of redirecting them back to the previous url?

This is a normal reaction of URL::previous , because after switching the language the URL::previous is changed to the last request and it will always do that. So in this case URL::previous won't help you here!

Cryank's avatar

@bobbybouwmann Yes, I got the point, but this I have many pages back to different pages by using URL::previous() as a common function placed on helper.php. Changes path every page might be painful for me :S

bobbybouwmann's avatar

Well in that case you need to find a way to redirect the user somewhere else if the previous url is equal to something with lang. Now you might do that for the posts view but I think you will have more views and pages so that will end up with a lot of if statements... I don't know any good solution right now.. I will come back to you if I have a solution ;)

Cryank's avatar

@bobbybouwmann , whoops , I think I get it wrong

if (!Session::has('edit_previous_button'))
      {
        Session::put('edit_previous_button', URL::previous());
      }

<a class="btn btn-info" href="{{ Session::get('edit_previous_button') }}">back</a>

Isn't it the back button still using URL::previous() ?

In my case no page will back to "/post/create", I may able to do this silly way to solve my problem,
well... I dont think this is a best practice ..

    $route = str_replace('/create','',URL::previous());
bobbybouwmann's avatar

Wel you need to set the session of course. It will default to URL::previous right now

Please or to participate in this conversation.