Courtney White
Courtney White

Reputation: 614

Redirect "method is not supported for this route"

I have an API endpoint that users can post to

Route::post('report', 'Auth\ReportController@report')

Because it only supports the POST request, if users were to go to mydomain.com/api/report they would get the error

The GET method is not supported for this route.

I don't want users to be able to type this in into their address bar and receive this error. So I make a get that redirects to home

 Route::get('report', function () {
    return redirect('home');
});

Is this the proper way to deal with this? Is there a more elegant solution? Also, is it possible to list multiple routes and have them all redirect to home, for example something like this:

 Route::get(['report', 'issuer'], function () {
        return redirect('home');
    });

Upvotes: 0

Views: 2823

Answers (2)

apokryfos
apokryfos

Reputation: 40730

I would strongly recommend you leave it alone since a 405 message for method not allowed is very informative to both API consumers as well as many people.

However if you must do this I suggest you use the exception handler

App\Exceptions\Handler (the boilerplate that comes with laravel can be seen at https://github.com/laravel/laravel/blob/master/app/Exceptions/Handler.php)

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;


class Handler extends ExceptionHandler
{
    public function render($request, Exception $exception)
    {
        if (!$request->expectsJson() && $exception instanceof MethodNotAllowedHttpException) {
            return redirect('home');
        } 

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

This should cause all MethodNotAllowedHttpException to be redirected to the homepage.

Note I also use condition !$request->expectsJson() because clients that expect JSON will typically not want to know about a redirect and instead would prefer to be notified of the real status code

Upvotes: 4

online Thomas
online Thomas

Reputation: 9401

More elegant:

Route::permanentRedirect('/report', '/home');

Even better might be to use API routes for your API, if you place your API routes in routes/api.php it will automatically prefix them with /api/[route]

To redirect a list of routes to home, use a wildcard route at the bottom and define the redirect in the controller.

Upvotes: 1

Related Questions