Learn or Die

生涯勉強。Macです。

ルーティングの優先度について

事象

下記のようなルーティングで、/sample/showにアクセスすると404エラーが発生する。

<?php

Route::get('/sample/{id}', 'SampleController@index');
Route::get('/sample/show', 'SampleController@show');

エラー原因

Laravelのルーティング設定では「上に書かれた設定が優先的に実行される」
そのため、/sample/showにアクセスすると「/sample/{id}」の方のルーティングが実行され、エラーが発生してしまう。

対処方法

ルーティングを入れ替え優先度を変更する。

<?php

Route::get('/sample/show', 'SampleController@show');
Route::get('/sample/{id}', 'SampleController@index');

もしくはルーティングに正規表現でバリデーションを付けるのも○。