Php MethodNotAllowedHttpException,重定向到404
这是一组控制器的列表:Php MethodNotAllowedHttpException,重定向到404,php,laravel,routes,Php,Laravel,Routes,这是一组控制器的列表: Route::group([ 'prefix' => 'some-prefix', ], function () { Route::get('/', 'MyController@index')->name('some-prefix'); Route::post('/get', 'MyController@getData')->name('some-prefix.get');
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
和edit
方法中放置了一个failOrFind
,这样我可以重播404条路由,如:
http://myapp.com/some-prefix/9999/edit
如果值
9999
不存在,但如何执行我的请求?转到App\Exception
打开handler.php
中的render()
方法添加:
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的答案作为正确答案,我只想与他提出的答案分享我的全部代码,顺便说一句,它有2个'n'的方法不允许HttpExceptionn
):
密码是什么MyController@update及MyController@edit? 因为它们接受一个动态参数,所以应该在那里处理404。我有一些代码需要更改…@leo请编辑您的代码
MethodNotAllowedHttpException
notMethodNotAllowedHttpException n
,最后注意两个“n”。谢谢,我也尝试了类似的方法,但没有成功。我会选择这一个作为正确的一个,因为我更喜欢触摸路由代码而不是处理程序,但问题是我有许多组类似的路由。。。(我的错误是代码设计不好,我应该使用资源
而不是get、post、put等)
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);
}