Razvan Zamfir
Razvan Zamfir

Reputation: 4664

How can fix this "GET method is not supported for this route" error in Laravel 8?

I am working on a Laravel 8 application that requires user registration and login.

There is a user profile page where the authenticated user can edit his/her own data.

In the routes file I have:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Frontend\HomepageController;
use App\Http\Controllers\Dashboard\DashboardController;
use App\Http\Controllers\Dashboard\UserProfileController;

Route::get('/', [HomepageController::class, 'index'])->name('homepage');

Auth::routes();

Route::group(['middleware' => ['auth']], function() {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/profile', [UserProfileController::class, 'index'])->name('profile');
    Route::post('/dashboard/profile/update', [UserProfileController::class, 'update'])->name('profile.update');
    Route::post('/dashboard/profile/deleteavatar/{id}/{fileName}', [UserProfileController::class, 'deleteavatar'])->name('profile.deleteavatar');
});

The problem

The method I need on the route /dashboard/profile/update is indeed POST.

Nevertheless, whenever I go to /dashboard/profile/update in the browser's address bar, I get the error:

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

I wish I did not get this error. The solutions I found on the Internet involved changing the method and other non-satisfactory methods.

Using Route::any fills the update form with validation errors.

Can I do a redirect to /dashboard/profile/ when (and only if) a GET method id executed on /dashboard/profile/update?

What is the simplest way to do that?

What is the better alternative to doing that?

Upvotes: 0

Views: 1497

Answers (2)

Peppermintology
Peppermintology

Reputation: 10220

Redirecting to another route if you get a request on it can be done very simply from your web.php:

Route::get('dashboard/profile/update', function () {
    return redirect(route('dashboard.profile'));
});

Upvotes: 1

John Lobo
John Lobo

Reputation: 15339

First you have to allow both get and post method in request.I have used any but we can use match also

 Route::any('/dashboard/profile/update', [UserProfileController::class, 'update'])->name('profile.update');

any will match all type of request.So you can match specific request like this

Route::match(['get', 'post'], '/dashboard/profile/update', [UserProfileController::class, 'update'])->name('profile.update');

then in your method

public function update(Request $request){
  
  if($request->isMethod('GET')){


  }
  if($request->isMethod('POST')){


  }
}

Upvotes: 2

Related Questions