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

# URL 生成

> 介绍 Laravel 的 url() 辅助函数、命名路由 URL、签名 URL、控制器动作 URL 的生成方式。

## 简介

Laravel 提供了若干辅助函数用来生成应用中的 URL。
在模板或 API 响应中构建链接、或生成指向应用其他位置的重定向响应时，它们特别有用。

## 基本用法

### 生成 URL

使用 `url` 辅助函数可以生成任意 URL。
生成的 URL 会自动使用当前请求所处理的 scheme（HTTP 或 HTTPS）和主机名。

```php theme={null}
$post = App\Models\Post::find(1);

echo url("/posts/{$post->id}");

// http://example.com/posts/1
```

要生成包含查询字符串参数的 URL，请使用 `query` 方法。

```php theme={null}
echo url()->query('/posts', ['search' => 'Laravel']);

// https://example.com/posts?search=Laravel

echo url()->query('/posts?sort=latest', ['search' => 'Laravel']);

// http://example.com/posts?sort=latest&search=Laravel
```

若指定了路径中已存在的查询参数，现有值将被覆盖。

```php theme={null}
echo url()->query('/posts?sort=latest', ['sort' => 'oldest']);

// http://example.com/posts?sort=oldest
```

也可以将数组作为查询参数传入。这些值会被正确地加键并编码到生成的 URL 中。

```php theme={null}
echo $url = url()->query('/posts', ['columns' => ['title', 'body']]);

// http://example.com/posts?columns%5B0%5D=title&columns%5B1%5D=body

echo urldecode($url);

// http://example.com/posts?columns[0]=title&columns[1]=body
```

### 获取当前 URL

调用 `url` 辅助函数时若不传入路径，会返回一个 `Illuminate\Routing\UrlGenerator` 实例，允许你访问当前 URL 的相关信息。

```php theme={null}
// 不含查询字符串的当前 URL
echo url()->current();

// 含查询字符串的当前 URL
echo url()->full();
```

这些方法也可以通过 `URL` [门面](./facades)访问。

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

echo URL::current();
```

### 获取上一个 URL

有时你需要知道用户在访问当前页面之前所在的 URL。可以通过 `url` 辅助函数的 `previous` 或 `previousPath` 方法来获取。

```php theme={null}
// 上一个请求的完整 URL
echo url()->previous();

// 上一个请求的路径
echo url()->previousPath();
```

也可以通过 Session 获取上一个 URL。

```php theme={null}
use Illuminate\Http\Request;

Route::post('/users', function (Request $request) {
    $previousUri = $request->session()->previousUri();

    // ...
});
```

还可以通过 Session 获取上一个访问的路由名。

```php theme={null}
$previousRoute = $request->session()->previousRoute();
```

## 命名路由的 URL

`route` 辅助函数可以用来生成[命名路由](./routing#named-routes)的 URL。
使用命名路由可以让你在生成 URL 时不依赖具体的实际 URL。
这样一来，即使某个路由的 URL 发生变化，也无需修改 `route` 函数的调用。

```php theme={null}
Route::get('/post/{post}', function (Post $post) {
    // ...
})->name('post.show');
```

要生成指向该路由的 URL，可以这样写：

```php theme={null}
echo route('post.show', ['post' => 1]);

// http://example.com/post/1
```

也支持带有多个参数的路由。

```php theme={null}
Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) {
    // ...
})->name('comment.show');

echo route('comment.show', ['post' => 1, 'comment' => 3]);

// http://example.com/post/1/comment/3
```

如果传入的数组元素中包含路由未定义的参数，它们会作为查询字符串附加到 URL 上。

```php theme={null}
echo route('post.show', ['post' => 1, 'search' => 'rocket']);

// http://example.com/post/1?search=rocket
```

### Eloquent 模型

在生成 URL 时，通常会使用 Eloquent 模型的路由键（一般为主键）。
因此，你可以直接把 Eloquent 模型作为参数值传入，`route` 辅助函数会自动取出模型的路由键。

```php theme={null}
echo route('post.show', ['post' => $post]);
```

### 签名 URL

Laravel 可以很方便地为命名路由创建「签名」URL。
这些 URL 会在查询字符串中附加一个「签名」哈希，Laravel 通过它验证 URL 创建后是否被篡改过。
签名 URL 特别适用于允许公开访问、但仍需防范 URL 篡改的路由。

例如，你可以用签名 URL 来实现邮件中发送给用户的公开「取消订阅」链接。
使用 `URL` 门面的 `signedRoute` 方法即可创建签名 URL。

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

return URL::signedRoute('unsubscribe', ['user' => 1]);
```

通过给 `signedRoute` 方法指定 `absolute` 参数，可以在签名 URL 哈希中排除域名。

```php theme={null}
return URL::signedRoute('unsubscribe', ['user' => 1], absolute: false);
```

要生成在指定时间后过期的临时签名 URL，请使用 `temporarySignedRoute` 方法。
Laravel 在校验临时签名 URL 时，会同时验证编码在 URL 中的过期时间戳尚未到达。

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

return URL::temporarySignedRoute(
    'unsubscribe', now()->plus(minutes: 30), ['user' => 1]
);
```

#### 签名 URL 的校验流程

```mermaid theme={null}
sequenceDiagram
    participant App as Laravel 应用
    participant User as 用户
    participant Mail as 邮件
    App->>App: URL::signedRoute() / temporarySignedRoute()
    App->>Mail: 通过邮件发送签名 URL
    Mail->>User: 收到邮件
    User->>App: 点击 URL（GET 请求）
    App->>App: 校验签名<br>hasValidSignature()
    alt 签名有效
        App->>User: 执行处理（如取消订阅）
    else 签名无效/过期
        App->>User: 403 错误
    end
```

#### 校验签名路由请求

要判断接收到的请求是否携带有效签名，可以调用 `Illuminate\Http\Request` 实例的 `hasValidSignature` 方法。

```php theme={null}
use Illuminate\Http\Request;

Route::get('/unsubscribe/{user}', function (Request $request) {
    if (! $request->hasValidSignature()) {
        abort(401);
    }

    // ...
})->name('unsubscribe');
```

如果希望在校验时忽略某些查询参数，可以使用 `hasValidSignatureWhileIgnoring` 方法。

```php theme={null}
if (! $request->hasValidSignatureWhileIgnoring(['page', 'order'])) {
    abort(401);
}
```

除了使用请求实例外，你也可以为路由分配 `signed`（`Illuminate\Routing\Middleware\ValidateSignature`）[中间件](./middleware)。
如果接收到的请求没有有效签名，中间件会自动返回 `403` 响应。

```php theme={null}
Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
})->name('unsubscribe')->middleware('signed');
```

如果签名 URL 不包含域名，请在中间件上指定 `relative` 参数。

```php theme={null}
Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
})->name('unsubscribe')->middleware('signed:relative');
```

#### 处理无效的签名路由

访问过期的签名 URL 时，会显示一个 `403` HTTP 状态的通用错误页面。
你可以在 `bootstrap/app.php` 中为 `InvalidSignatureException` 定义自定义 render 闭包来自定义此行为。

```php theme={null}
use Illuminate\Routing\Exceptions\InvalidSignatureException;

->withExceptions(function (Exceptions $exceptions): void {
    $exceptions->render(function (InvalidSignatureException $e) {
        return response()->view('errors.link-expired', status: 403);
    });
})
```

## 控制器动作的 URL

`action` 函数用于生成指向指定控制器动作的 URL。

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

$url = action([HomeController::class, 'index']);
```

如果控制器方法接收路由参数，请把路由参数关联数组作为第二个参数传入。

```php theme={null}
$url = action([UserController::class, 'profile'], ['id' => 1]);
```

## 流式 URI 对象

Laravel 的 URI 类提供了一种流式接口，可以通过对象方式创建和操作 URI。

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

// 从字符串创建 URI 实例
$uri = Uri::of('https://example.com/path');

// 生成指向路径、命名路由或控制器动作的 URI
$uri = Uri::to('/dashboard');
$uri = Uri::route('users.show', ['user' => 1]);
$uri = Uri::signedRoute('users.show', ['user' => 1]);
$uri = Uri::temporarySignedRoute('user.index', now()->plus(minutes: 5));
$uri = Uri::action([UserController::class, 'index']);

// 从当前请求 URL 创建 URI 实例
$uri = $request->uri();
```

获取到 URI 实例后，可以流式地修改它。

```php theme={null}
$uri = Uri::of('https://example.com')
    ->withScheme('http')
    ->withHost('test.com')
    ->withPort(8000)
    ->withPath('/users')
    ->withQuery(['page' => 2])
    ->withFragment('section-1');
```

## 默认 URL 参数

有时你希望对某个 URL 参数在整个请求生命周期中都指定一个默认值。
例如许多路由都定义了 `{locale}` 参数。

```php theme={null}
Route::get('/{locale}/posts', function () {
    // ...
})->name('post.index');
```

每次调用 `route` 辅助函数都要传入 `locale` 十分繁琐。
你可以使用 `URL::defaults` 方法，在当前请求中始终应用该参数的默认值。
如果在[路由中间件](./middleware#assigning-middleware-to-routes)中调用该方法，就可以直接访问当前请求。

```php theme={null}
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;

class SetDefaultLocaleForUrls
{
    /**
     * 处理传入的请求。
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        URL::defaults(['locale' => $request->user()->locale]);

        return $next($request);
    }
}
```

一旦为 `locale` 参数设置了默认值，使用 `route` 辅助函数生成 URL 时就不必再传入该值。

<Info>
  设置默认 URL 参数可能会干扰 Laravel 的隐式模型绑定。
  请通过[中间件优先级设置](./middleware#sorting-middleware)，让设置默认 URL 参数的中间件在 Laravel 的 `SubstituteBindings` 中间件之前执行。
  可以在 `bootstrap/app.php` 中使用 `priority` 中间件方法进行设置。

  ```php theme={null}
  ->withMiddleware(function (Middleware $middleware): void {
      $middleware->prependToPriorityList(
          before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
          prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
      );
  })
  ```
</Info>


## Related topics

- [Laravel Sail](/zh/sail.md)
- [路由](/zh/routing.md)
- [Laravel Wayfinder 介绍](/zh/blog/wayfinder-introduction.md)
- [Laravel Folio](/zh/folio.md)
- [字符串操作（Str 类）](/zh/strings.md)
