checker284
checker284

Reputation: 1316

Laravel 5.x: How to replace locale in URL in view/blade?

I've a blade in my views, which looks like this:

@if (App::getLocale() == 'de')
    <a href="/en/dashboard">
        <i class="fa fa-language">ENGLISH</i>
    </a>
@elseif (App::getLocale() == 'en')
    <a href="/de/dashboard">
        <i class="fa fa-language">GERMAN</i>
    </a>
@endif

This creates a button, which allows me to switch to the other language.

Well... The URL could also be one of these:

/en/settings
/en/logbook

I want, that the button redirects to the same page, but on a different language:

Using {{ Request::url() }} I'm able to get the current URL, but what's now the best way / solution to use this URL just with a different locale?

{{ Request::url() }} for example contains /en/dashboard and I would now need /de/dashboard.

Does there any Laravel function exist or do I need to code this with PHP within... The blade?

Upvotes: 1

Views: 1817

Answers (2)

Rashad
Rashad

Reputation: 1344

I would prefer this way.

public static function getLocaleChangerURL($locale)
{
    $uri = request()->segments();

    $uri[0] = $locale;

    return implode($uri, '/');
}

Upvotes: 2

Buglinjo
Buglinjo

Reputation: 2077

I have wrote this small helper function about 2 years ago. It works great when you pass $locale variable and it adds it to URL's first segment.

 public static function getLocaleChangerURL($locale){
    $uri = $_SERVER['REQUEST_URI'];
    $uri = explode('/', $uri);
    unset($uri[0]);
    unset($uri[1]);
    $url = url($locale);
    foreach($uri as $u){
        $url .= '/'.$u;
    }
    return $url;
}

Upvotes: 4

Related Questions