I want to redirect my post route to error page if the request is not made with post but with get method. But i am getting the error "The GET method is not supported for this route. Supported methods: POST."
My route file
Route::get('/user/create',[UserController::class, 'create'])->name('user.create');
Route::post('/user',[UserController::class, 'store'])->name('user.store');
Into my controller i have used
public function store(Request $request){
if($request->isMethod('POST')){
dd($request->all());
}else{
return abort(404);
}
}
So when the route is Route::post('/user',[UserController::class, 'store'])->name('user.store');
for submitting the data by post method the url is http://127.0.0.1:8000/admin/user
ok i dont have any problem with that, but when i do hit into my urlbar http://127.0.0.1:8000/admin/user
with get method i get the above error but i dont want to show that rather it should get redirected to error page.
CodePudding user response:
It's the logic to get a bad method error when someone is requesting a bad method but you can do something like this:
routes file:
Route::any('/user',[UserController::class, 'store'])->name('user.store');
and in controller:
public function store(Request $request){
if(! $request->isMethod('POST')){
return abort(404);
}
// and the rest of your code for the post request.
}
In case you don't want to edit the routes you can replace the exception.
in app/Exceptions/Handler.php add render method:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $e)
{
if ($e instanceof MethodNotAllowedHttpException) {
return abort(404);
}
return parent::render($request, $e);
}
}