cariboufute/locale-route

A testable route package with localization for Laravel 5 to 10

3.0.3 2023-03-20 18:05 UTC

README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

LocaleRoute is a package to make testable localized routes with Laravel 5 to 10. It comes from the need to have localized routes that are fully testable.

LocaleRoute has a syntax close to the original Laravel routing methods, so the installation and learning curve should be quite easy.

For an example of LocaleRoute implementation, please check my locale-route-example repo.

Change log

Please see changelog for more information what has changed recently and what will be added soon.

Requirements

Please choose your version of LocaleRoute according to your version of Laravel.

Install

First install the package through Composer by typing this line in the terminal at the root of your Laravel application.

composer require cariboufute/locale-route

For Laravel 5.4 and earlier

Since Laravel 5.5, Package Discovery installs service provider and LocaleRoute alias automatically. But if you have Laravel 5.4 and earlier, add the service provider and the LocaleRoute alias in config/app.php.

// config/app.php

'providers' => [
    //...
    CaribouFute\LocaleRoute\LocaleRouteServiceProvider::class,
    //...
],

'aliases' => [
    //...
    'LocaleRoute' => CaribouFute\LocaleRoute\Facades\LocaleRoute::class,
],

Middleware

In your app/Http/Kernel.app file, add the SetLocale middleware in the web middleware group. This will read the locale from the locale session variable, saved by each localized route and will keep the locale for redirections, even after using unlocalized routes to access models CRUD routes, for instance.

// app/Http/Kernel.app

protected $middlewareGroups = [
    'web' => [
        //...
        \CaribouFute\LocaleRoute\Middleware\SetLocale::class,
    ],

    //...
];

Config file

Finally install the config file of the package by typing this line in the terminal at the root of your Laravel application.

php artisan vendor:publish

To bypass the package selection prompt, type this line instead.

php artisan vendor:publish --provider "CaribouFute\LocaleRoute\LocaleRouteServiceProvider"

Then you should have a config/localeroute.php installed.

Configuration

Check your config/localeroute.php file. Here is the default file.

// config/localeroute.php

<?php

return [

    /**
     * The locales used by routes. Add all
     * locales needed for your routes.
     */
    'locales' => ['fr', 'en'],

    /**
     * Option to add '{locale}/' before given URIs.
     * For LocaleRoute::get('route', ...):
     * true     => '/fr/route'
     * false    => '/route'
     * Default is true.
     */
    'add_locale_to_url' => true,
];

Locales

Add all the locale codes needed for your website in locales.

For instance, if you want English, French, Spanish and German in your site...

    'locales' => ['en', 'fr', 'es', 'de'],

Add locale automatically to URLs

This option is by default set to true. It prepends all URLs build by locale-route with a {locale}/, according to Google Multi-regional and multilingual sites guidelines.

If for any reason, you don't want this prefix to be added automatically, just put this option to false, like this.

    'add_locale_to_url' => false,

Usage

Adding routes

Adding localized routes is now really easy. Just go to your routes/web.php file (or app/Http/routes.php in older versions of Laravel) and add LocaleRoute declarations almost like you would declare Laravel Route methods.

// routes/web.php or app/Http/routes.php

LocaleRoute::get('route', 'Controller@getAction', ['fr' => 'url_fr', 'en' => 'url_en']);
LocaleRoute::post('route', 'Controller@postAction', ['fr' => 'url_fr', 'en' => 'url_en']);
LocaleRoute::put('route', 'Controller@putAction', ['fr' => 'url_fr', 'en' => 'url_en']);
LocaleRoute::patch('route', 'Controller@patchAction', ['fr' => 'url_fr', 'en' => 'url_en']);
LocaleRoute::delete('route', 'Controller@deleteAction', ['fr' => 'url_fr', 'en' => 'url_en']);
LocaleRoute::options('route', 'Controller@optionsAction', ['fr' => 'url_fr', 'en' => 'url_en']);
LocaleRoute::any('route', 'Controller@getAction', ['fr' => 'url_fr', 'en' => 'url_en']);

For the first line, it is the equivalent of declaring this in pure Laravel, while having the app locale set to the right locale.

Route::get('fr/url_fr', ['as' => 'fr.route', 'uses' => 'Controller@getAction']);
Route::get('en/url_en', ['as' => 'en.route', 'uses' => 'Controller@getAction']);

You can also give a string as locale URL if it is the same for all locales

LocaleRoute::get('route', 'Controller@getAction', 'url');

/*
    This will give these routes.

    ['fr.route']    =>  'fr/url'
    ['en.route']    =>  'en/url'
*/

Now, trailing methods are supported with LocaleRoute, as with the original Laravel Route facade.

//Example with URL parameter and trailing where method
LocaleRoute::get('show', 'Controller@show', ['fr' => 'url_fr/{id}', 'en' => 'url_en/{id}'])
    ->where(['id' => '[1-9]');
/*
    These routes will exist...

    ['fr.route']    =>  'fr/url_fr/1'
    ['en.route']    =>  'en/url_en/1'

    ...but not these routes.
    ['fr.route']    =>  'fr/url_fr/0'
    ['en.route']    =>  'en/url_en/0'
 */

So the syntax can be resumed to this.

LocaleRoute::{method}({routeName}, {Closure or controller action}, {locale URL string or array with 'locale' => 'url'});

Using translator files for URLs

You can also use the Laravel translator to put all your locale URLs in resources/lang/{locale}/routes.php files. If there is no locale URL array, LocaleRoute will automatically check for the translated routes.php files to find URLs. All you need to do is to remove the locale URL array in LocaleRoute and declare them as 'route' => 'url' in your translated route files, like this.

// routes/web.php or app/Http/routes.php

LocaleRoute::get('route', 'Controller@routeAction');
// resources/lang/en/routes.php

return [
    'route' => 'url_en',
]
// resources/lang/fr/routes.php

return [
    'route' => 'url_fr',
]

Note about localized and unlocalized routes using same base URL

If you declare localized and unlocalized routes using the same base URL, please declare your LocaleRoute method before the Route method. If you don't, the normal route will be discarded by the locale route attribution process.

For instance, if you declare a normal route with "/" to redirect to the fallback locale (for instance, "/en") before the localized routes (for instance, "/en" and "/fr"), the localized routes with replace the first route before being added the locale. Declaring locale routes before the normal unlocalized route will cause no problems.

/**
 * Here, the '/' URL will be discarded. Only "/fr" and "/en" will exist.
 */

Route::get('/', function () {
    return redirect('/fr');
});

LocaleRoute::get('index', 'PublicController@index', ['fr' => '/', 'en' => '/']);


/**
 * Here, all routes with work fine : "/", "/fr" and "/en".
 */

LocaleRoute::get('index', 'PublicController@index', ['fr' => '/', 'en' => '/']);

Route::get('/', function () {
    return redirect('/fr');
});

Middleware

If you want to use middleware for your LocaleRoute, add them in the url array (3rd parameter) in the 'middleware' key.

//routes/web.php or app/Http/routes.php

LocaleRoute::get('route', 'Controller@getAction', ['fr' => 'url_fr', 'en' => 'url_en', 'middleware' => 'guest']);

//To use trans files URL, just add 'middleware'
LocaleRoute::get('route', 'Controller@getAction', ['middleware' => 'guest']);

Grouping

You can use the LocaleRoute methods inside normal Route::group methods.

// routes/web.php or app/Http/routes.php


Route::group(['as' => 'article.', 'prefix' => 'article'], function () {
    LocaleRoute::get('create', 'ArticleController@index', ['fr' => 'creer', 'en' => 'create']);
    Route::post('store', ['as' => 'store', 'uses' => 'ArticleController@store']);
});

/*
Will give these routes :

[fr.article.create] => GET  "/fr/article/creer"     => ArticleController::create()
[en.article.create] => GET  "/en/article/create"    => ArticleController::create()
[article.store]     => POST "/article/store"        => ArticleController::store()
*/

Resource

To add a localized RESTful resource, just use LocaleRoute::resource() with the same syntax as Route::resource. This will give localized routes for all GET/HEAD routes and will keep the POST/PUT/PATCH/DELETE routes unlocalized.

// routes/web.php or app/Http/routes.php

LocaleRoute::resource('article', 'ArticleController');

/*
Will give these routes :

[fr.article.index]  => GET/HEAD     "/fr/article"                   => ArticleController::index()
[en.article.index]  => GET/HEAD     "/en/article"                   => ArticleController::index()
[fr.article.show]   => GET/HEAD     "/fr/article/{article}"         => ArticleController::show()
[en.article.show]   => GET/HEAD     "/en/article/{article}"         => ArticleController::show()
[fr.article.create] => GET/HEAD     "/fr/article/create"            => ArticleController::create()
[en.article.create] => GET/HEAD     "/en/article/create"            => ArticleController::create()
[article.store]     => POST         "/article"                      => ArticleController::store()
[fr.article.edit]   => GET/HEAD     "/fr/article/{article}/edit"    => ArticleController::edit()
[en.article.edit]   => GET/HEAD     "/en/article/{article}/edit"    => ArticleController::edit()
[article.update]    => PUT/PATCH    "/article/{article}"            => ArticleController::update()
[article.destroy]   => DELETE       "/article/{article}"            => ArticleController::destroy()
*/

If you want to translate the create and edit words in resources routes URL, add route-labels.php lang files in the resources/lang folder with translation for create and edit.

// resources/lang/fr/route-labels.php

return [
    'create' => 'creer',
    'edit' => 'editer',
];
// resources/lang/en/route-labels.php

return [
    'create' => 'create',
    'edit' => 'edit',
];
// routes/web.php or app/Http/routes.php
LocaleRoute::resource('article', 'ArticleController');

/*
Will give these routes :

[fr.article.create] => GET/HEAD     "/fr/article/creer"             => ArticleController::create()
[en.article.create] => GET/HEAD     "/en/article/create"            => ArticleController::create()
[fr.article.edit]   => GET/HEAD     "/fr/article/{article}/editer"  => ArticleController::edit()
[en.article.edit]   => GET/HEAD     "/en/article/{article}/edit"    => ArticleController::edit()
...
*/

API resource

You can also use LocaleRoute::apiResource() for the localized version of Route::apiResource(), which corresponds to LocaleRoute::resource() without the create and edit pages. The translated route labels will be the same as for LocaleRoute::resource().

// routes/web.php or app/Http/routes.php

LocaleRoute::apiResource('article', 'ArticleController');

/*
Will give these routes :

[fr.article.index]  => GET/HEAD     "/fr/article"                   => ArticleController::index()
[en.article.index]  => GET/HEAD     "/en/article"                   => ArticleController::index()
[fr.article.show]   => GET/HEAD     "/fr/article/{article}"         => ArticleController::show()
[en.article.show]   => GET/HEAD     "/en/article/{article}"         => ArticleController::show()
[article.store]     => POST         "/article"                      => ArticleController::store()
[article.update]    => PUT/PATCH    "/article/{article}"            => ArticleController::update()
[article.destroy]   => DELETE       "/article/{article}"            => ArticleController::destroy()
*/

Overriding options

You can override the locale and add_locale_to_url config options simply by declaring them in the url array.

/*
    Config::get('localeroute.locales') => ['fr', 'en']
    Config::get('localeroute.add_locale_to_url') => true
*/

LocaleRoute::get('index', 'Controller@index', ['fr' => '/', 'en' => '/']);

/*
    ['fr.index']    => '/fr'
    ['en.index']    => '/en'
*/

LocaleRoute::get('create', 'Controller@create', [
        'fr' => 'creer',
        'en' => 'create',
        'de' => 'erstellen',
        'locales' => ['fr', 'en', 'de']
]);

/*
    ['fr.create']    => '/fr/creer'
    ['en.create']    => '/en/create'
    ['de.create']    => '/de/erstellen'
*/

LocaleRoute::get('store', 'Controller@store', [
        'fr' => 'stocker',
        'en' => 'store',
        'add_locale_to_url' => false
]);

/*
    ['fr.store']    => '/stocker'
    ['en.store']    => '/store'
*/

Fetching URLs

LocaleRoute gives three helper functions to help you get your URLs quickly. They are close to the Laravel route helper function.

locale_route

This is the basic helper function. It calls the URL according to the locale, route name and parameters. When put to null, locale and route are set to the current values.

//locale_route($locale, $route, $parameters)

locale_route('fr', 'route');                //gets the French route URL.
locale_route('es', 'article', ['id' => 1]); //gets the Spanish article route URL with parameter 'id' set to 1
locale_route(null, 'index');                //gets the index route URL in the current locale
locale_route('en');                         //gets the current URL in English
locale_route('en', null, ['id' => 1]);      //gets the current URL in English, with parameter 'id' set to 1

For the last three situations, there are clearer helper functions.

other_route

Calls another route URL in the same locale. The syntax is the same as Laravel route.

//other_route($route, $parameters)

other_route('route');                   //gets the route URL in the current locale.
other_route('article', ['id' => 1]);    //gets the article route URL in the current locale with parameter 'id' to 1 in the current locale
other_route('article')                  //gets the article route URL in the current locale with no parameters.

other_locale

Calls the same route URL in another locale. For the syntax, we just replace the route name by the locale. Perfect for language selectors.

//other_locale($locale, $parameters)

other_locale('es');                     //gets the same URL in Spanish.
other_locale('en', ['id' => 1]);        //gets the same URL in English with parameter 'id' to 1.
other_locale('fr')                      //gets the same URL in French with current parameters.
other_locale('de', [])                  //gets the same URL in German with no parameters, when there are parameters in the current route.

Contributing

Please see contributing and conduct for details.

Credits

License

The MIT License (MIT). Please see License File for more information.