2
votes

I am translating my Laravel website, which uses the mcamara/laravel-localization package for translation. I have found that if somebody types a not existing language (f.e. http://localhost/de/test) there are some errors on the page. Because I don't want to check and repair all pages for that errors, I need some Middleware or Handler to check if the selected language is in the array with the translations and if not to redirect to 404 page.

Unfortunately I am not sure where to make that check ?

if(!in_array($lang, $languages)) {
    App::abort(404);
}
return true;

Many thanks !

1
I believe showing a 404 page might not be the best practice. Would you rather consider creating a fallback/default language and always redirect there instead of 404? - Jax297

1 Answers

1
votes

have you considered that the language should be on a query string instead of part of the endpoint? for example http://localhost/test?lang=de i've seen many developers take this approach and i believe it's more clean.

Regarding your question it seems you already have the right idea on the middleware so create a new one and check Illuminate\Translation\Translator there are several methods there that could help you determine if the translation exists.

Example:

public function handle($request, Closure $next)
{
    if (Illuminate\Support\Facades\Lang::hasForLocale($someKey,$request->lang)) {
        abort(404);
    }

    return $next($request);
}

$someKey could be a string you always configure to be translated, $request->lang could be a segment of the request if you use (/de/test).

Another approach could be to check (!file_exists($path)) $path being your translation file, and then redirect.

Hope this helps.