php - Laravel language switcher, pass additional parameters to a route

one text

Solution:

You can achieve it with the following steps:

  • Implement a URL generator macro which will make much easier to generate your URLs which must be identical except language
  • Get the current route's parameters
  • Merge the chosen language into them
<?php

namespace App\Providers;

use Illuminate\Routing\UrlGenerator;
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()
    {
        UrlGenerator::macro('toLanguage', function (string $language) {
            $currentRoute = app('router')->current();
            $newRouteParameters = array_merge(
                $currentRoute->parameters(), compact('language')
            );
            return $this->route($currentRoute->getName(), $newRouteParameters);
        });
    }
}

And in your Blade file

@inject('app', 'Illuminate\Contracts\Foundation\Application')
@inject('urlGenerator', 'Illuminate\Routing\UrlGenerator')

<language-switcher
    locale="{{ $app->getLocale() }}"
    link-en="{{ $urlGenerator->toLanguage('en') }}"
    link-bg="{{ $urlGenerator->toLanguage('bg') }}"
></language-switcher>

You'll notice I used contracts injection instead of using facades. More informations here https://laravel.com/docs/7.x/contracts#contracts-vs-facades

And if you don't known Laravel macros, more informations here https://tighten.co/blog/the-magic-of-laravel-macros

Source