'Customise the "method is not supported for this route" error handling in Laravel

Route::post('order', 'OrderController@store')->name('order');

When I browse to the URL http://127.0.0.1:8000/order it shows the error:

The GET method is not supported for this route. Supported methods: POST.

Which is the correct.

But I want to redirect user to home page instead of showing this error.



Solution 1:[1]

First of all note that what you are trying to do seems like an anti-pattern for Laravel. Accessing a route with the wrong method should be denied!

I currently do not know about altering the default way of handling the wrong method error and I wouldn't advise to do that. But you can work around it:

Patching

Method 1

Keep your routes file clean but alter the original route line and add some lines to the beggining of the controller method

Route::match(['get', 'post'], 'order', [OrderController::class, 'store'])->name('order');
    public function store(Request $request)
    {
        if ($request->isMethod('get')) {
            return to_route('home');
        }
        // ...

Method 2

Keep your controller clean, but add a line to your routes file

Route::get('order', fn () => to_route('home'));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1