エンジニアのひよこ_level10

毎日更新してた人。たまに記事書きます。

【Laravel】route.phpの書き順で動かなくなるパターン。例題あり。【180日目】

書き方間違えてないはず、なぜか反応しない

// ①
Route::get('/', 'TopController@index')->name('top');
// ②
Route::get('/{name}', 'ProfileController@detail)->name('profile_detail');
// ③
Route::get('/list', 'ProfileController@list')->name('profile_list');

どれが反応しないのか

原因はこれ

// ①
Route::get('/', 'TopController@index')->name('top');
// ②
Route::get('/{name}', 'ProfileController@detail)->name('profile_detail'); //←こいつのせい
// ③
Route::get('/list', 'ProfileController@list')->name('profile_list'); //←これ反応しない

なぜ反応しないのか

https://domain.co.jp/
https://domain.co.jp/user_name
https://domain.co.jp/list

この時、3番目のURLは③のルートになりそうだけれども、②のルートが反応する。

書き順のせいで、②が優先されて、nameにlistが代入されたと判断されて、②が動いてしまう。

route.phpの書き順も意外と重要

ということで、何も考えずにrouteを書いていると、思わぬところでハマるので気をつけましょう。

私はこれで1時間ハマりました|||orz