5.

MethodNotAllowedHttpException No message

編集
この記事の要点
  • MethodNotAllowedHttpExceptionHTTP メソッド (GET/POST/PUT/DELETE 等) がルートに合わないとき発生
  • 原因 ①: フォームの method がルート定義と違う
  • 原因 ②: PUT/PATCH/DELETE で @method ディレクティブ忘れ
  • 原因 ③: ルート定義のメソッド名タイポ
  • エラー画面の "Allow" ヘッダで許可されているメソッドを確認

 

エラーの状況

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.

# または
The POST method is not supported for this route. Supported methods: GET, HEAD.

Laravel が「このルートはそのメソッドでは呼べない」と判断したエラー。HTTP 仕様としては 405 Method Not Allowed

主な原因と対処

原因 1: フォームの method 属性が違う

// routes/web.php
Route::post('/users', [UserController::class, 'store']);


@csrf ...
@csrf ...

原因 2: PUT/PATCH/DELETE で @method 忘れ

HTML フォームは GET / POST しか直接送信できない。PUT/PATCH/DELETE はPOST + _method パラメータで送信する必要がある:

// routes/web.php
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);


@csrf
@csrf @method("PUT")
@csrf @method("DELETE")

原因 3: Route::get と Route::post の登録ミス

// ダメな例
Route::get('/users/store', [UserController::class, 'store']);  // POST にすべき

// フォームから POST で送信
// → GET ルートしかないので 405

// 修正
Route::post('/users', [UserController::class, 'store'])->name('users.store');

原因 4: Resource Controller の HTTP メソッド忘れ

// Route::resource はモダンな REST 慣習に従う
Route::resource('users', UserController::class);

// 生成されるルート:
// GET    /users           → index
// GET    /users/create    → create
// POST   /users           → store
// GET    /users/{id}      → show
// GET    /users/{id}/edit → edit
// PUT    /users/{id}      → update     ← PUT
// PATCH  /users/{id}      → update     ← PATCH
// DELETE /users/{id}      → destroy    ← DELETE

// 確認
// $ php artisan route:list

原因 5: Ajax / fetch のメソッド指定漏れ

// ダメな例
fetch("/api/users/1", {
    body: JSON.stringify({ name: "Alice" })
    // method 指定なし → デフォルト GET
});
// route が PUT なら 405

// 修正
fetch("/api/users/1", {
    method: "PUT",
    headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken
    },
    body: JSON.stringify({ name: "Alice" })
});

// axios
axios.put("/api/users/1", { name: "Alice" });
axios.patch("/api/users/1", { status: "active" });
axios.delete("/api/users/1");

原因 6: api.php と web.php の区別

// routes/api.php (URL prefix: /api)
Route::post('/users', [UserController::class, 'store']);

// routes/web.php
Route::post('/users', [UserController::class, 'store']);

// /api/users と /users は別のルート
// クライアントから誤って /api/users にリクエストして /users と認識される逆もあり

route:list で確認

# 全ルート一覧
$ php artisan route:list

  GET|HEAD     /                   home.index
  GET|HEAD     users               users.index
  POST         users               users.store
  GET|HEAD     users/create        users.create
  GET|HEAD     users/{id}          users.show
  GET|HEAD     users/{id}/edit     users.edit
  PUT|PATCH    users/{id}          users.update
  DELETE       users/{id}          users.destroy

# 特定のパスで絞り込み
$ php artisan route:list --path=users

# 特定の HTTP メソッド
$ php artisan route:list --method=POST

レスポンスヘッダで許可メソッド確認

$ curl -I -X GET http://localhost/users/1
HTTP/1.1 405 Method Not Allowed
Allow: PUT, PATCH, DELETE  ← 許可されているメソッド

API でカスタムエラーレスポンス

// app/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
    if ($exception instanceof MethodNotAllowedHttpException) {
        return response()->json([
            'error' => 'method_not_allowed',
            'message' => 'このリソースに対する HTTP メソッドが正しくありません',
            'allowed_methods' => $exception->getHeaders()['Allow'] ?? '',
        ], 405);
    }
    return parent::render($request, $exception);
}

関連エラー

エラー意味
NotFoundHttpException (404)ルート自体が存在しない
MethodNotAllowedHttpException (405)このページのエラー
TokenMismatchException (419)CSRF トークン不一致
AuthorizationException (403)権限不足
ValidationException (422)バリデーション失敗

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost'
  2. Add [~] to fillable property to allow mass assignment on [App\~].
  3. PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in ~
  4. Changing columns for table "~" requires Doctrine DBAL; install "doctrine/dbal"
  5. MethodNotAllowedHttpException No message
  6. Class 'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
  7. production.ERROR: No application encryption key has been specified.
  8. Dotenv values containing spaces must be surrounded by quotes.
  9. Laravel \ Socialite \ Two \ InvalidStateException
  10. The page has expired due to inactivity. Please refresh and try again.
  11. Failed to clone https://github.com/symfony/thanks.git via https, ssh protocol
  12. Illegal offset type
  13. Cannot access protected property Illuminate\Http\Request::$...
  14. Emitted value instead of an instance of Error
  15. 画像保存時にInternal Server Error
  16. Failed to authenticate on SMTP server with username ...
  17. PostTooLargeException
  18. Database hosts array is empty.
  19. Invalid request (Unsupported SSL request)
  20. does not comply with psr-4 autoloading standard. Skipping.
  21. MySQLのSTR_TO_DATE関数を使用するとnullが返却される問題