クマのブログ

つまづいたところ、学びを書いていきます

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

前提

  • Windows

  • Laravel : 6.0

  • MySQL : 5.7

  • 実務で使用予定のLaravelをUdemyで学習中につまずいた

状況

RESTfulなリソースコントローラにより、CRUD機能を実装していた時。 具体的には"store"メソッドを実装しようとしていた

困ったこと

  • コントローラ、ルーティング、ビューのファイルを各々以下のように記述し、dd($your_name)で値が取得できているか確認

↓コントローラ

<?php
・
・
・
    public function store(StoreContactForm $request)
    {
        $contact = new ContactForm;

        $contact->your_name = $request->input('your_name');
        $contact->title = $request->input('title');
        $contact->email = $request->input('email');
        $contact->url = $request->input('url');
        $contact->gender = $request->input('gender');
        $contact->age = $request->input('age');
        $contact->contact = $request->input('contact');

        dd($your_name);
    }
・
・
・
?>

↓ルーティング

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('tests/test', 'TestController@index');

Route::group(['prefix'=> 'contact', 'middleware'=>'auth'], function(){
    Route::get('index', 'ContactFormController@index')->name('contact.index');
    Route::get('create', 'ContactFormController@create')->name('contact.create');
    Route::get('store', 'ContactFormController@store')->name('contact.store');  //上記createのルーティングをコピー・修正して作成

?>

↓ビュー

 <form method="POST" action="{{route('contact.store')}}">
  @csrf
  氏名
  <input type="text" name="your_name">
 <br>
   件名
  <input type="text" name="title">
 ・
 ・
  <input class="btn btn-info" type="submit" value="登録する">
  </form>
  • 表示結果は以下の通りのエラー f:id:kuma_kuma0121:20210409212522p:plain The POST method is not supported for this route. Supported methods: GET, HEAD.

なんのこっちゃわからず、調べる

やったこと

教材と比較してコードの記述に相違ないか?

仮説

教材の中で何か見落とした結果、このエラーが発生しているのではないか?

対策

以下Laravel日本語ドキュメントの表について言及している点を見返した。 f:id:kuma_kuma0121:20210409213439p:plain

readouble.com

これによるとstoreメソッドに対応する動詞はpostであることが分かったためここを修正

↓ルーティング(修正版)

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('tests/test', 'TestController@index');

Route::group(['prefix'=> 'contact', 'middleware'=>'auth'], function(){
    Route::get('index', 'ContactFormController@index')->name('contact.index');
    Route::get('create', 'ContactFormController@create')->name('contact.create');
    Route::post('store', 'ContactFormController@store')->name('contact.store');  // getをpostに修正

?>

結果

無事dd($your_name)の結果が表示 

備考

学習教材からとはいえ、一次情報からエラー解決の糸口を引っ張ることができたのはよかった