0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Route::matchについて

Last updated at Posted at 2022-01-07

同じURLのルーティングをまとめる事ができるRoute::match

Route::get ('sample/aaa',  'HogeController@index')->name('hoge.index');
Route::post('sample/aaa',  'HogeController@index')->name('hoge.index');

このように、リクエストがgetなのかpostなのか、が違うだけで2行書かなければいけないところをRoute::matchを使う事で、

Route::match(['get', 'post'], 'foo','HogeController@index')->name('hoge.index');

とまとめることができる。

getとpostで異なるアクションにしたい場合の使い方

Route::get ('sample/aaa',  'HogeController@index')->name('hoge.index');
Route::post('sample/aaa',  'HogeController@postIndex')->name('hoge.index');

このようなpostとgetで呼び出すアクションが異なる処理を

Route::match(['get', 'post'], 'foo','HogeController@index')->name('hoge.index');

このようにまとめてしまうと、当然アクションを分けることができません。
そのため以下のように、Controller内でリクエスト種別を判定して処理を分岐させる必要があります。

    public function index(Request $request)
    {
        if ($request->method() == 'POST')    //POSTだったら
        {
            return $this->postIndex($request);    //postIndexへ
        }
 
        return view('hoge/index');
    }
 
    public function postIndex(Request $request)
    {
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?