【问题标题】:How can fix this "GET method is not supported for this route" error in Laravel 8?如何修复 Laravel 8 中的“此路由不支持 GET 方法”错误?
【发布时间】:2021-06-05 06:33:42
【问题描述】:

我正在开发一个需要用户注册和登录的 Laravel 8 application

有一个用户个人资料页面,经过身份验证的用户可以编辑他/她自己的数据。

在我的路由文件中:

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');
});

问题

我在路由/dashboard/profile/update上需要的方法确实是POST。

不过,每当我在浏览器的地址栏中转到 /dashboard/profile/update 时,我都会收到错误消息:

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

我希望我没有收到此错误。我在网上找到的解决方案包括改变方法和其他不令人满意的方法。

使用Route::any 会在更新表单中填写验证错误。

当(并且仅如果)在/dashboard/profile/update 上执行 GET 方法 ID 时,我可以重定向到 /dashboard/profile/ 吗?

最简单的方法是什么?

这样做有什么更好的选择?

【问题讨论】:

  • 可能是你的路由文件被缓存了,试试php artisan route:clear ?
  • @Espresso 我已经这样做了。
  • Route::any method ?
  • @JohnLobo 使用 Route::any 会在更新表单中填写验证错误。
  • 根据我的理解,任何路由都应该允许所有方法。你也可以显示表单和控制器代码

标签: php laravel laravel-8


【解决方案1】:

首先,您必须在请求中同时允许 get 和 post 方法。我使用了 any,但我们也可以使用 match

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

any 将匹配所有类型的请求。因此您可以像这样匹配特定请求

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

然后在你的方法中

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


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


  }
}

【讨论】:

  • 我试过if($request->isMethod('GET')){ return redirect()->route('profile'); }。这是有道理的。但它不起作用。必须弄清楚原因。
  • 我认为match在这种情况下是最好的,因为他只需要检查2个动词。
【解决方案2】:

如果您收到关于它的请求,可以非常简单地从您的web.php 重定向到另一条路线:

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

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 2021-08-05
    • 2021-01-10
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2021-10-07
    • 2021-05-08
    相关资源
    最近更新 更多