How to translated URL endpoint in Laravel php?

51 Views Asked by At

In Laravel, how can I accomplish url endpoint translation?

I want to translate my endpoint using the language that I have chosen in Ruby on Rails. Is it possible to accomplish this? For instance, when I translate or switch languages in - Englist -> DomainName.com/home, let's say I have the language French -> DomainName.com/maison.

I'm trying to define two different URLs in both languages to do this, but I'd like to discover the most efficient method.

1

There are 1 best solutions below

0
On

We can achieve this by -

  1. Create Language Files: Create language files for each language you want to support in the resources/lang directory. For example, you might have routes.php files for English and French:

    lang/
        ├── en/
        │   └── routes.php
        └── fr/
            └── routes.php
    
    // lang/en/routes.php
    return [
        'home' => 'home',
    ];
    
    // lang/fr/routes.php
    return [
        'home' => 'maison',
    ];
    
  2. Create a Helper to Translate Routes: Define a helper function to translate route names in your application. Create a helper file (e.g., Helpers.php) if you don't have one, and add the following function:

    // app/Helpers.php
    if (!function_exists('langRoute')) {
        function langRoute($value)
        {
            return trans("routes.$value");
        }
    }
    

    Make sure to autoload this file in your composer.json:

    "autoload": {
        "files": [
            "app/Helpers.php"
        ]
    }
    

    Then run composer dump-autoload to refresh the autoloader.

  3. Define Route with Translated Name: In your web.php routes file, use the langRoute helper to define routes with translated names:

    // routes/web.php
    use App\Http\Controllers\HomeController;
    
    Route::get(langRoute('home'), [HomeController::class, 'index'])->name('home');
    
  4. Generate Translated URLs: In your Blade views, use the route function with the translated route name to generate URLs dynamically:

    <a href="{{ route('home') }}">Home</a>
    
  5. Set Locale in Middleware: Create a middleware to set the application locale based on user preferences or the language specified in the URL:

    
        app()->setLocale($userLocale);