Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 route prefix

Tags:

php

laravel-5

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

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

My idea was to do so:

<?php

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

This works. My problem is that I'd like to autoload the Country for each sub route and be able to use it from the controller as well as the view.

Any hints?

like image 966
greut Avatar asked Nov 08 '15 11:11

greut


2 Answers

The solution, I've came up with relies on a 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 the 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 meant for a swiss application, hence the _CH everywhere.

like image 84
greut Avatar answered Oct 01 '22 19:10

greut


One way to achieve this is using the segment function of the Request facade:

$country = Request::segment(1);
like image 44
svrnm Avatar answered Oct 01 '22 17:10

svrnm