> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 路由

> 介绍 Laravel 中定义路由的方式、路由参数、命名路由等基础知识。

## 基础路由

Laravel 最基础的路由由 URI 和闭包组成。
无需复杂的配置文件即可轻松定义路由与对应行为。

```php theme={null}
use Illuminate\Support\Facades\Route;

Route::get('/greeting', function () {
    return 'Hello World';
});
```

### 默认的路由文件

Laravel 所有的路由都定义在 `routes/` 目录下的路由文件中。
Laravel 会根据 `bootstrap/app.php` 的配置自动加载这些文件。

```mermaid theme={null}
flowchart LR
    A["传入的请求"] --> B{{"请求类型"}}
    B -->|"面向浏览器<br>Session / CSRF"| C["routes/web.php<br>web 中间件组"]
    B -->|"面向 API<br>无状态"| D["routes/api.php<br>api 中间件组"]
    B -->|"CLI 命令"| E["routes/console.php<br>定义 Artisan 命令"]
    C --> F["控制器 / 闭包"]
    D --> F
    E --> G["命令处理器"]
```

`routes/web.php` 用于定义面向浏览器的路由。
此文件的路由会应用 `web` 中间件组，从而提供 Session、CSRF 保护与 Cookie 加密。

```php theme={null}
use App\Http\Controllers\UserController;

Route::get('/user', [UserController::class, 'index']);
```

### API 路由

如果应用要提供无状态 API，可以通过 `install:api` Artisan 命令启用 API 路由。

```shell theme={null}
php artisan install:api
```

`install:api` 命令会安装 [Laravel Sanctum](/zh/sanctum) 并创建 `routes/api.php` 文件。
Sanctum 提供了一种简洁而稳固的 API 令牌认证守卫，适用于第三方 API 消费者、SPA 和移动应用。

```php theme={null}
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:sanctum');
```

`routes/api.php` 中的路由是无状态的，并会应用 `api` [中间件组](/zh/middleware)。
同时会自动为所有路由添加 `/api` 前缀，无需手动指定。
如果要修改前缀，请编辑应用的 `bootstrap/app.php` 文件。

```php theme={null}
->withRouting(
    api: __DIR__.'/../routes/api.php',
    apiPrefix: 'api/admin',
    // ...
)
```

### 可用的 HTTP 方法

路由器可以注册对应任意 HTTP 方法的路由。

```php theme={null}
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
```

要注册响应多种 HTTP 方法的路由，请使用 `match` 或 `any`。

```php theme={null}
Route::match(['get', 'post'], '/', function () {
    // ...
});

Route::any('/', function () {
    // ...
});
```

<Info>
  在 `web` 路由文件中接收 `POST`、`PUT`、`PATCH`、`DELETE` 的 HTML 表单，务必包含 `@csrf` 指令。
  否则请求将被拒绝。
</Info>

## 返回视图的路由

如果路由只需返回视图，可以用 `Route::view` 更简洁地定义。

```php theme={null}
Route::view('/welcome', 'welcome');

// 向视图传递数据
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
```

## 路由参数

### 必需参数

如果要动态获取 URL 的一部分，请使用路由参数。
参数用 `{}` 包裹，并作为路由回调的参数接收。

```php theme={null}
Route::get('/user/{id}', function (string $id) {
    return '用户 ID: ' . $id;
});
```

可以定义多个参数。

```php theme={null}
Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
    return "文章 {$postId} 的评论 {$commentId}";
});
```

<Warning>
  路由参数不能包含 `/` 字符。
</Warning>

### 可选参数

若要让参数变为可选，请在参数名末尾添加 `?`，并给对应参数设置默认值。

```php theme={null}
Route::get('/user/{name?}', function (?string $name = null) {
    return $name ?? '访客';
});

Route::get('/user/{name?}', function (?string $name = '访客') {
    return $name;
});
```

### 正则表达式约束参数

使用 `where` 方法可以用正则表达式约束参数的格式。

```php theme={null}
Route::get('/user/{id}', function (string $id) {
    // ...
})->where('id', '[0-9]+');

Route::get('/user/{name}', function (string $name) {
    // ...
})->where('name', '[a-zA-Z]+');
```

常用模式还可以通过便捷方法书写。

```php theme={null}
Route::get('/user/{id}/{name}', function (string $id, string $name) {
    // ...
})->whereNumber('id')->whereAlpha('name');
```

## 命名路由

命名路由可以在生成 URL 或重定向时通过路由名进行引用。

```php theme={null}
Route::get('/user/profile', function () {
    // ...
})->name('profile');
```

### 通过命名路由生成 URL

使用 `route` 辅助函数可以根据路由名生成 URL。

```php theme={null}
// 生成 URL
$url = route('profile');

// 生成带参数的 URL
$url = route('user.show', ['id' => 1]);
```

### 重定向

```php theme={null}
return redirect()->route('profile');
```

## 路由分组

可以将相关路由分组，共享中间件、控制器、前缀等设置。

```mermaid theme={null}
flowchart TD
    A["HTTP 请求"] --> B["路由器"]
    B --> C{{"是否有匹配<br>的路由？"}}
    C -->|"否"| D["返回 404"]
    C -->|"是"| E["检查该路由的中间件"]
    E --> F{{"中间件是否<br>通过？"}}
    F -->|"拒绝"| G["重定向 /<br>错误响应"]
    F -->|"通过"| H["执行控制器 /<br>闭包"]
    H --> I["生成响应"]
    I --> J["返回给客户端"]
```

### 中间件

```php theme={null}
Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', function () {
        // 仅已认证用户可访问
    });

    Route::get('/account', function () {
        // 仅已认证用户可访问
    });
});
```

### 控制器

可以将使用同一个控制器的路由分组。

```php theme={null}
use App\Http\Controllers\OrderController;

Route::controller(OrderController::class)->group(function () {
    Route::get('/orders', 'index');
    Route::post('/orders', 'store');
    Route::get('/orders/{id}', 'show');
});
```

### 前缀

可以为路由 URI 添加公共前缀。

```php theme={null}
Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // 可通过 /admin/users 访问
    });
    Route::get('/posts', function () {
        // 可通过 /admin/posts 访问
    });
});
```

## 查看路由列表

要列出所有已定义的路由，请使用 Artisan 命令。

```shell theme={null}
php artisan route:list
```

若要一并显示中间件信息，可以：

```shell theme={null}
php artisan route:list -v
```

若只显示以特定 URI 开头的路由，可以：

```shell theme={null}
php artisan route:list --path=user
```

## 下一步

<Card title="视图" icon="eye" href="/zh/views">
  学习如何创建视图，并从控制器向视图传递数据。
</Card>


## Related topics

- [路由](/zh/packages/laravel-bluesky/route.md)
- [请求生命周期](/zh/lifecycle.md)
- [Laravel Socialite（社交登录）](/zh/socialite.md)
- [Laravel Sentinel — 路由保护中间件调查](/zh/blog/sentinel-introduction.md)
- [邮件验证（Email Verification）](/zh/verification.md)
