2017-10-19 143 views
0

這是一組控制器的名單:MethodNotAllowedHttpException,重定向到404

Route::group([ 
     'prefix'  => 'some-prefix', 
    ], function() { 
     Route::get('/', '[email protected]')->name('some-prefix'); 
     Route::post('/get', '[email protected]')->name('some-prefix.get'); 
     Route::get('/getall/{type}', '[email protected]')->name('some-prefix.getall'); 
     Route::get('/create', '[email protected]')->name('some-prefix.create'); 
     Route::post('/', '[email protected]')->name('some-prefix.store'); 
     Route::get('/edit', '[email protected]')->name('some-prefix.edit'); 
     Route::get('/{id}/edit/', '[email protected]')->name('some-prefix.edit'); 
     Route::put('/{id}', '[email protected]')->name('some-prefix.update'); 
     Route::get('/cambiarestado/{id}', '[email protected]')->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) 

我把我的failOrFindstoreedit種方法在我的控制器,這樣我就可以redict到404條路線,如:

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

其中值9999不存在,但我怎麼能做到什麼,我問?

+0

什麼是@ myController的更新和@ myController的編輯的代碼?由於這些接受一個動態參數,你應該在那裏處理404。 – Devon

回答

2

轉到App\Exceptionrender()方法添加開拓handler.php

public function render($request, Exception $exception) 
    { 
     if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpExceptionn){ 
      return abort('404'); 
      } 
     return parent::render($request, $exception); 
    } 
+0

我加入了一些新的生產線也在那裏,讓我們來看看。我有一些代碼,應改變... – pmirnd

+1

@leo請編輯代碼'MethodNotAllowedHttpException'不'MethodNotAllowedHttpExceptionn',注意在最後兩個「N」。 –

1

你可以做這樣的事情在你的路線:

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

謝謝,我是想這樣的事情也沒有成功。我會選這一個爲正確的,因爲我喜歡觸摸路由代碼要比處理程序,但問題是,我有類似的航線多組...(我對糟糕的代碼設計的錯,我應該用'resource'取而代之,發佈,放等) – pmirnd

0

這是我做的(我撿的答案@Leo_Kelmendi爲正確的,我只是想分享我的,他把過多的一個整個代碼,順便說一下它有2個「N」的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); 
}