繁体   English   中英

MethodNotAllowedHttpException,重定向到404

[英]MethodNotAllowedHttpException, redirect to 404

这是一组控制器的列表:

Route::group([
        'prefix'     => 'some-prefix',
    ], function () {
        Route::get('/', 'MyController@index')->name('some-prefix');
        Route::post('/get', 'MyController@getData')->name('some-prefix.get');
        Route::get('/getall/{type}', 'MyController@getAllData')->name('some-prefix.getall');
        Route::get('/create', 'MyController@create')->name('some-prefix.create');
        Route::post('/', 'MyController@store')->name('some-prefix.store');
        Route::get('/edit', 'MyController@edit')->name('some-prefix.edit');
        Route::get('/{id}/edit/', 'MyController@edit')->name('some-prefix.edit');
        Route::put('/{id}', 'MyController@update')->name('some-prefix.update');
        Route::get('/cambiarestado/{id}', 'MyController@cambiarestado')->name('some-prefix.cambiarestado');
    });

我在键入URL时要重定向到404错误:

http://myapp.com/some-prefix/ANYTHING-that-doesnt-match

这是我收到下一个错误的时候:

(1/1) MethodNotAllowedHttpException
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('PUT'))
in RouteCollection.php (line 238)
at RouteCollection->getRouteForMethods(object(Request), array('PUT'))
in RouteCollection.php (line 176)

我在我的store里放了一个failOrFind并在我的控制器中edit方法,所以我可以改写为404路线,如:

http://myapp.com/some-prefix/9999/edit

9999不存在的地方,但我怎么能按照我的要求去做?

转到App\\Exception开拓handler.phprender()方法中加入:

 public function render($request, Exception $exception)
 {
    if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException){
      return abort('404');
    }

    return parent::render($request, $exception);
 }

您可以在路线中执行以下操作:

Route::get('/some-prefix/{any}', function () {
    return abort('404');
})->where('any', '.*');

这就是我所做的(我选择@Leo_Kelmendi作为正确答案的答案,我只是想将他的整个代码与他所提出的代码分享,顺便说一下,它的方法是MethodNotAllowedHttpExceptionn ):

public function render($request, Exception $exception)
{
    /*
     * Redirect if token mismatch error
     * Usually because user stayed on the same screen too long and their session expired
     */
    if ($exception instanceof TokenMismatchException) {
        return redirect()->route('frontend.auth.login');
    }

    /*
     * All instances of GeneralException redirect back with a flash message to show a bootstrap alert-error
     */
    if ($exception instanceof GeneralException) {
        return redirect()->back()->withInput()->withFlashDanger($exception->getMessage());
    }

    if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException){
        return abort('404');
    }

    return parent::render($request, $exception);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM