Martin AJ Martin AJ - 1 year ago 86
PHP Question

Master routing page in Laravel

Former I had created my own MVC and there was an

that all pages passed from the way of it. I mean, I could put a redirect (
header('Location: ..');
) into
, and then none of my website pages can not be opened.

Now I use Laravel and I need a core-page (like
). Because my new website supports multi-languages. Here is my current code:

// app/Http/routes.php
Route::get('/{locale?}', 'HomeController@index');

// app/Http/Controllers/HomeController.php
public function index($locale = null)
if(!is_null($locale)) {

/* http://localhost:8000 => output: en -- default
* http://localhost:8000/abcde => output: en -- fallback language
* http://localhost:8000/en => output: en -- defined language
* http://localhost:8000/es => output: es -- defined language
* http://localhost:8000/fa => output: fa -- defined language

As you see, in my current algorithm, I need to check the language that the user has set for each route. Also my website has almost 30 routes. I can do that manually 30 times for each route, but I think there is a way which lets me to do that once for all routes. Isn't there?

In other word, how can I set current language (the user has set) for each page? Should I check/set it for each route separately?

Answer Source

There is a smarter way in Laravel for solve your trouble. It is called Middleware. So you can just create LangMiddleware and put your logic inside.

Something like

public function handle($request, Closure $next, $locale = null)
    if ($locale && in_array($locale, config('app.allowed_locales'))) {

    return $next($request);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download