DEV Community

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

Collapse
chonz0 profile image
chonz0

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){
    dump(request()->fullUrl());
    dd(redirect()->back()->getTargetUrl());
});
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

Cheers!

Collapse
inshasamad18 profile image
inshasamad18

when i run this code i got an error page not found. the url should be like this 127.0.0.1:8000/localisation/create but when i change the language the url become 127.0.0.1:8000/localisation/lang/en.