Laravel redirect to correct path on missing routes

2019-07-29 14:23发布

问题:

In my application when user enter this url as http://127.0.0.1:8000/showContent/aboutUs laravel show error as an

Sorry, the page you are looking for could not be found.

for that correct path is http://127.0.0.1:8000/en/showContent/aboutUs and I'm trying to manage that and adding missing segment for that for example:

Route:

Route::get('{lang?}/showContent/aboutUs', array('as' => 'lang', 'uses' => 'HomeController@showAboutUsPage'))->where('lang', '.+');

mapping routes:

protected function mapWebRoutes()
{
    $locale = request()->segment(1);
    if ($locale != 'fa' && $locale != 'en') {
        $locale = 'fa';
    }
    app()->setLocale($locale);


    Route::middleware('web')
        ->namespace($this->namespace)
        ->prefix($locale)
        ->group(base_path('routes/web.php'));
}

on mapWebRoutes function i'm using multi language and manage routes, and for missing parameters as language key on segment(1) I get error, now how can I add missing segment or manage routes to redirect to correct path?

回答1:

sorry for duplicate comment! it is related to your web server. you can use .htaccess file for that. another way is to use exception handler. you can check the exception type and also the request route. then redirect to appropriate url if it is necessary.



回答2:

My problem solved:

i change kernel.php to :

protected $middleware = [
    \App\Http\Middleware\Language::class,

    ...

];

and Language class to:

public function handle($request, Closure $next)
{
    $locale = $request->segment(1);

    if (!array_key_exists($locale, config('app.locales'))) {
        $segments = $request->segments();
        array_unshift($segments,config('app.fallback_locale'));
        return redirect(implode('/', $segments));
    }

    app()->setLocale($locale);

    return $next($request);
}