Laravel redirect to correct path on missing routes

我只是一个虾纸丫 提交于 2019-12-24 08:59:36

问题


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);
}


来源:https://stackoverflow.com/questions/48043352/laravel-redirect-to-correct-path-on-missing-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!