ofat/laravel-translatable-routes

Laravel package for translatable routes

v1.0.1 2022-04-28 09:42 UTC

This package is auto-updated.

Last update: 2024-04-28 14:16:22 UTC


README

68747470733a2f2f7777772e6e7973656e6174652e676f762f73697465732f64656661756c742f66696c65732f7374796c65732f373630783337372f7075626c69632f70726573732d72656c656173652f6d61696e2d696d6167652f66625f6c696e6b5f737570706f72745f756b7261696e653732372e6a7067

Package to make Laravel routes translatable

Latest Version on Packagist MIT Licensed

This package provides you possibility to translate your urls. For example:

EN: /en/country/germany, /en/about-us
DE: /de/land/deutschland, /de/uber-uns

It is very useful for good search engine optimization (seo).

Installation

  1. Install package via composer:
composer require ofat/laravel-translatable-routes 
  1. Add your translations to resource/lang like usual Laravel translations.

resources/lang/en.json:

{
    "country": "Country",
    "about-us": "About us"
}

resources/lang/de.json:

{
    "country": "Land",
    "about-us": "Uber uns"
}
  1. Define your supported locales in config file:

config/translatable-routes.php:

return [
    'locales' => ['en', 'de']
];

Routing

Once the package is installed you can use your translation strings in route defining with square brackets.

To define group with added language prefix you can use localeGroup method and write all routes inside it.

Route::localeGroup(function() {
    Route::get('[country]/{country}', function($country) {
    
    });
    Route::get('[about-us]', function(){
        return 'hi!';
    });
});

Named Routes

You can also use names for your routes inside localeGroup. It will create separate route name for each locale:

Route::localeGroup(function(){
    Route::get('[country]/{country}', function($country){
    
    })->name('country')
});

URL Generating

Generate URL by route

You can use normal route function to generate url in current locale:

route('country', ['country' => $country]);

url()->route('country', ['country' => $country])

Depends on current locale it will create /en/country/... or /de/land/...

You can use routeInLocale method if you need to generate URL in concrete locale or just add locale in your route name:

routeInLocale('de', 'country', ['country' => $country]);

url()->routeInLocale('de', 'country', ['country' => $country]);

route('de.country', ['country' => $country]);

Generate URL by path

You can also use translation keys in square brackets in url function. But it doesn't add locale prefix to your URL

url('[country]/belgium')

url()->to('[country]/belgium')

To add locale prefix to your url:

url()->withLocale('[country]/belgium'); // generates `en/country/belgium`

urlWithLocale('[country]/belgium');

urlWithLocale('[country]/belgium', $params, 'en'); // specify needed locale. generates `de/land/belgium`

Locale switch

To generate url for language switching you can use named route switch-locale

route('switch-locale', 'fr')

All static routes will be switching by default. But for routes with parameters you can add strategies and define logic for translation:

namespace App\Service\UrlTranslator;

use App\Models\Country;
use Ofat\LaravelTranslatableRoutes\UrlTranslator\Abstracts\BaseUrlTranslation;

class CountryUrlTranslation extends BaseUrlTranslation
{
    /**
     * Get current route translated url
     * 
     * @param string $locale
     * @return string
     */
    public function getTranslatedUrl(string $locale): string
    {
        $country = Country::query()
            ->where('url->'.$this->route->getLocale(), $this->route->parameter('country'))
            ->firstOrFail();

        return $this->urlGenerator->route('country', $country->url);
    }

    /**
     * Check if current route is applicable to this strategy
     *
     * @return bool
     */
    public function isApplicable(): bool
    {
        return strpos($this->route->getName(), '.country') > 0;
    }
}

In this case if you try to switch language on page /en/country/france it will redirect to /fr/les-pays/la-france

In isApplicable method you should write your logic for checking if route is determined to your group needs.

In getTranslatedUrl method you should write your logic to generate url for your route on new locale