Laravel 5 Route Prefix

I would like to have a route preceded by a country. Like this:

/us/shop
/ca/shop
/fr/shop

My idea was to do this:

<?php

Route::group([
    'prefix' => '{country}'
], function() {
    Route::get('shop', 'ShopController@Index');
    // ...
});

It works. My problem is that I would like to autoload Countryfor each submap and be able to use it both from the controller and the view.

Any clues?

+4
source share
2 answers

The solution I came up with depends on the specific middleware.

<?php

Route::get('', function() {
    return redirect()->route('index', ['language' => App::getLocale()]);
});

Route::group([
    'prefix' => '{lang}',
    'where' => ['lang' => '(fr|de|en)'],
    'middleware' => 'locale'
], function() {

    Route::get('', ['as' => 'index', 'uses' => 'HomeController@getIndex']);

    // ...

}

and middleware.

<?php

namespace App\Http\Middleware;

use App;
use Closure;
use View;

class Localization {
    public function handle($request, Closure $next) {
        $language = $request->route()->parameter('lang');

        App::setLocale($language);

        // Not super necessary unless you really want to use
        // number_format or even money_format.
        if ($language == "en") {
            setLocale(LC_ALL, "en_US.UTF-8");
        } else {
            setLocale(LC_ALL, $language."_CH.UTF-8");
        }

        View::share('lang', $language);

        return $next($request);
    }
}

As you can guess, this code was intended for a swiss application, so _CHeverywhere.

+1
source

segment Request:

$country = Request::segment(1);
+1

Source: https://habr.com/ru/post/1614935/


All Articles