DEV Community

Discussion on: Adding multi-language functionality in a website developed in laravel.

chonz0 profile image

TL;DR: how to fix a potential "too many redirects" error calling redirect()->back()

Nice article, thanks! Although, if you enter the locale URL directly on the browser URL bar, you could get a "too many redirects" error.
The underlaying problem is, in that particular case, you don't have a "back" URL (as the current URL is the first in the history stack, so Laravel returns the current URL when you call redirect()->back())
You can see it yourself by adding the following:

Route::get('locale/{locale}', function ($locale){
Enter fullscreen mode Exit fullscreen mode

A quick fix would be to only call the back() method, if the target URL is different than the current one. You could achieve this by using the following snippet:

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

    if (request()->fullUrl() === redirect()->back()->getTargetUrl()) {
        return redirect('/');

    return redirect()->back();
Enter fullscreen mode Exit fullscreen mode


inshasamad18 profile image

when i run this code i got an error page not found. the url should be like this but when i change the language the url become