Routing 将 URL 和 HTTP 方法映射到处理它们的代码。在 Laravel 中,您在路由文件(routes/web.php、routes/api.php)中使用 Route facade 定义路由,将每个路由指向闭包或控制器方法。
基本路由
php
\\\;
::(, fn() => );
::(, [::, ]);
::(, [::, ]);
::(, [::, ]);
::(, [::, ]);
每个 HTTP 方法都有一个 Route:: 助手。路由指向闭包(对于简单情况)或更常见的 [Controller::class, 'method'] 对。
Route::get('/users/{id}', function ($id) { // {id} captured and passed in
return User::find($id);
});
Route::get('/posts/{post?}', fn($post = null) => ...); // optional parameter
Route::get('/profile', [ProfileController::class, 'show'])->name('profile');
// generate URLs by NAME — refactor-safe (change the URL in one place)
route('profile'); // → "/profile"
redirect()->route('profile');
// in Blade: <a href="{{ route('profile') }}">Profile</a>
命名路由 让您在任何地方按名称引用路由,而不是硬编码 URL — 因此更改 URL 不会破坏链接(这是一种 DRY、可维护的做法)。
// group routes with shared middleware/prefix
Route::middleware('auth')->prefix('admin')->group(function () {
Route::get('/dashboard', ...); // → /admin/dashboard, requires auth
});
// resource routes — all 7 RESTful routes for a controller at once
Route::resource('posts', PostController::class);
// → index, create, store, show, edit, update, destroy automatically
Route::resource 为控制器生成一整套 RESTful 路由 — 标准 CRUD 的最少代码。
路由是每个 Laravel 应用程序的基础 — 它定义了应用的 URL 并将它们连接到处理程序,因此理解它是构建任何端点的必要日常知识。
了解如何为每个 HTTP 方法定义路由、捕获参数、将路由指向控制器,以及使用组组织它们(用于共享中间件/前缀)是构建应用程序结构所必需的。
两种做法特别重要:命名路由(按名称而非硬编码 URL 引用路由 — 这是一个关键的可维护性优势,能防止 URL 更改时链接断裂),以及 资源路由(Route::resource,用一行为控制器生成所有标准 RESTful 路由 — 这是 CRUD 的一个主要生产力功能)。
路由连接了入口点(URL)与应用逻辑(控制器),使其成为构建结构良好的 Laravel 应用程序的核心、必知材料,而命名路由和资源路由约定反映了该框架对清晰、DRY、RESTful 设计的重视。