Laravel 8 路由顺序从下到上

Laravel 8 route order from bottom to top

我已经安装了 Laravel 8 并且运行良好,然后我尝试学习路由并尝试制作一些像这样的路由

Route::view('testing', 'welcome')->name('testingWelcome');
Route::get('testing',[TestingController::class, 'noParameter'])->name('testingNoParam');
Route::view('testing', 'dashboard')->name('testingDashboard');

这里有些 post 说 web.php 中的路由是从上到下工作的。但是,这不是我调用 url http://localhost/laraps/public/testing 时得到的结果。它总是被称为底部的。我试图更改顺序,但仍然是最后一个。

这个有什么解释吗?还是我配置有误?

感谢您的帮助

对此的简短解释是,每次调用 Route::{verb} 都会在您的路由集合 (relevant code) 下创建一个新的路由条目。 {verb} 禁止使用任何 HTTP 动词,例如getpost 等。此条目是在数组条目 [{verb}][domain/url].

下创建的

这意味着当一个新的路由被注册时匹配相同的 URL 和相同的方法它会覆盖旧的。

所以在这种情况下

Route::view('testing', 'welcome')->name('testingWelcome');
Route::get('testing',[TestingController::class, 'noParameter'])->name('testingNoParam');
Route::view('testing', 'dashboard')->name('testingDashboard');

只有第三个声明真正“坚持”。在某些情况下,多个路由定义可以匹配相同的 URL 例如假设您有这些路由:

Route::view('testing', 'welcome')->name('testingWelcome');
Route::get('testing/{optionalParameter?}',[TestingController::class, 'parameter'])->name('testingNoParam');
Route::view('testing/{otherParameter?}', 'dashboard')->name('testingDashboard');

在这种情况下,所有 3 条路由都添加到路由集合中,但是当访问 URL example.com/testing 时,第一个 匹配的路由将是在这种情况下将调用 welcome 视图。这是因为由于声明了所有 3 条路由,一旦路由器找到一条匹配的路由,它就会停止寻找更多的匹配项。

注意:通常没有必要声明多条完全相同的路由 URL,所以这主要是一个学术练习。但是,通常有一个用例,例如model/{id} 和 model/list` 以区分获取特定模型的信息和获取模型列表。在这种情况下,将路由声明为很重要:

Route::get('model/list',  [ ModelController::class, 'list' ]);
Route::get('model/{id}',  [ ModelController::class, 'view' ]);

但是您可以使用以下方法在路由声明中更加明确:

Route::get('model/{id}',  [ ModelController::class, 'view' ])->where('id', 
'\d+');
Route::get('model/list',  [ ModelController::class, 'list' ]);

在这种情况下,顺序无关紧要,因为 Laravel 知道 id 只能是一个数字,因此不会匹配 model/list