Martin AJ Martin AJ - 1 month ago 12
PHP Question

Master routing page in Laravel

Former I had created my own MVC and there was an

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

Now I use Laravel and I need a core-page (like
index.php
). 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)) {
Lang::setLocale($locale);
}

dd(Lang::getLocale());
/* 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

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'))) {
        Lang::setLocale($locale);
    }
    else{
        Lang::setLocale(config('app.fallback_locale'));
    }

    return $next($request);
}