
# URL 生成

-   [简介](#introduction)
-   [基础知识](#the-basics)
    -   [生成 URL](#generating-urls)
    -   [访问当前 URL](#accessing-the-current-url)
-   [命名路由的 URL](#urls-for-named-routes)
    -   [签名 URL](#signed-urls)
-   [控制器操作的 URL](#urls-for-controller-actions)
-   [流式 URI 对象](#fluent-uri-objects)
-   [默认值](#default-values)

## 简介

Laravel 提供了多个辅助函数，用于帮助你为应用程序生成 URL。这些辅助函数主要用于在模板和 API 响应中构建链接，或者生成重定向响应到应用程序的其他部分。

## 基础知识

### 生成 URL

`url` 辅助函数可用于为你的应用程序生成任意 URL。生成的 URL 会自动使用当前应用程序正在处理的请求中的协议（HTTP 或 HTTPS）和主机：

```php
$post = App\Models\Post::find(1);

echo url("/posts/{$post->id}");

// http://example.com/posts/1
```

要生成带有查询字符串参数的 URL，可以使用 `query` 方法：

```php
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
echo url()->query('/posts?sort=latest', ['sort' => 'oldest']);

// http://example.com/posts?sort=oldest
```

也可以将值数组作为查询参数传递。这些值会在生成的 URL 中被正确设置键名并进行编码：

```php
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 生成

-   [简介](#introduction)
-   [基础知识](#the-basics)
    -   [生成 URL](#generating-urls)
    -   [访问当前 URL](#accessing-the-current-url)
-   [命名路由的 URL](#urls-for-named-routes)
    -   [签名 URL](#signed-urls)
-   [控制器操作的 URL](#urls-for-controller-actions)
-   [流式 URI 对象](#fluent-uri-objects)
-   [默认值](#default-values)

## 简介

Laravel 提供了多个辅助函数，用于帮助你为应用程序生成 URL。这些辅助函数主要用于在模板和 API 响应中构建链接，或者生成重定向响应到应用程序的其他部分。

## 基础知识

### 生成 URL

`url` 辅助函数可用于为你的应用程序生成任意 URL。生成的 URL 会自动使用当前应用程序正在处理的请求中的协议（HTTP 或 HTTPS）和主机：

```php
$post = App\Models\Post::find(1);

echo url("/posts/{$post->id}");

// http://example.com/posts/1
```

要生成带有查询字符串参数的 URL，可以使用 `query` 方法：

```php
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
echo url()->query('/posts?sort=latest', ['sort' => 'oldest']);

// http://example.com/posts?sort=oldest
```

也可以将值数组作为查询参数传递。这些值会在生成的 URL 中被正确设置键名并进行编码：

```php
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
// 获取当前 URL（不包含查询字符串）...
echo url()->current();

// 获取当前 URL（包含查询字符串）...
echo url()->full();
```

这些方法中的每一个也可以通过 `URL` [门面](/docs/laravel/13.x/facades) 进行访问：

```php
use Illuminate\Support\Facades\URL;

echo URL::current();
```

#### 访问之前的 URL

有时，了解用户访问来源的上一个 URL 是很有帮助的。你可以通过 `url` 辅助函数的 `previous` 和 `previousPath` 方法访问之前的 URL：

```php
// 获取上一次请求的完整 URL...
echo url()->previous();

// 获取上一次请求的路径...
echo url()->previousPath();
```

或者，通过 [session](/docs/laravel/13.x/session)，你可以将之前的 URL 作为一个流式 URI实例进行访问：

```php
use Illuminate\Http\Request;

Route::post('/users', function (Request $request) {
    $previousUri = $request->session()->previousUri();

    // ...
});
```

也可以通过 session 获取之前访问 URL 对应的路由名称：

```php
$previousRoute = $request->session()->previousRoute();
```

## 命名路由的 URL

`route` 辅助函数可用于为[命名路由](/docs/laravel/13.x/routing#named-routes)生成 URL。命名路由允许你生成 URL，而无需与路由中实际定义的 URL 产生耦合。因此，如果路由的 URL 发生变化，则无需修改调用 `route` 函数的代码。例如，假设你的应用程序包含如下定义的路由：

```php
Route::get('/post/{post}', function (Post $post) {
    // ...
})->name('post.show');
```



要为此路由生成 URL，可以像下面这样使用 `route` 辅助函数：

```php
echo route('post.show', ['post' => 1]);

// http://example.com/post/1
```

当然，`route` 辅助函数也可以用于为具有多个参数的路由生成 URL：

```php
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
echo route('post.show', ['post' => 1, 'search' => 'rocket']);

// http://example.com/post/1?search=rocket
```

#### Eloquent 模型

你经常会使用 [Eloquent 模型](/docs/laravel/13.x/eloquent)的路由键（通常是主键）来生成 URL。因此，你可以将 Eloquent 模型作为参数值传递。`route` 辅助函数会自动提取模型的路由键：

```php
echo route('post.show', ['post' => $post]);
```

### 签名 URL

Laravel 允许你轻松地为命名路由创建“签名” URL。这些 URL 会在查询字符串中附加一个“签名”哈希值，使 Laravel 可以验证该 URL 自创建以来是否被修改过。签名 URL 对于那些可以公开访问但需要防止 URL 被篡改的路由特别有用。

例如，你可以使用签名 URL 来实现一个发送给客户的公开“取消订阅”链接。要为命名路由创建签名 URL，可以使用 `URL` 门面的 `signedRoute` 方法：

```php
use Illuminate\Support\Facades\URL;

return URL::signedRoute('unsubscribe', ['user' => 1]);
```



你可以通过向 `signedRoute` 方法提供 `absolute` 参数，将域名从签名 URL 哈希中排除：

```php
return URL::signedRoute('unsubscribe', ['user' => 1], absolute: false);
```

如果你想生成一个在指定时间后过期的临时签名路由 URL，可以使用 `temporarySignedRoute` 方法。当 Laravel 验证临时签名路由 URL 时，它会确保编码在签名 URL 中的过期时间戳尚未失效：

```php
use Illuminate\Support\Facades\URL;

return URL::temporarySignedRoute(
    'unsubscribe', now()->plus(minutes: 30), ['user' => 1]
);
```

#### 验证签名路由请求

要验证传入的请求是否具有有效签名，你应该在传入的 `Illuminate\Http\Request` 实例上调用 `hasValidSignature` 方法：

```php
use Illuminate\Http\Request;

Route::get('/unsubscribe/{user}', function (Request $request) {
    if (! $request->hasValidSignature()) {
        abort(401);
    }

    // ...
})->name('unsubscribe');
```

有时，你可能需要允许应用程序的前端向签名 URL 添加数据，例如在执行客户端分页时。因此，你可以使用 `hasValidSignatureWhileIgnoring` 方法指定在验证签名 URL 时应该忽略的请求查询参数。请记住，忽略参数意味着任何人都可以修改请求中的这些参数：

```php
if (! $request->hasValidSignatureWhileIgnoring(['page', 'order'])) {
    abort(401);
}
```

除了使用传入的请求实例验证签名 URL 外，你还可以将 `signed` (`Illuminate\Routing\Middleware\ValidateSignature`) [中间件](/docs/laravel/13.x/middleware) 分配给路由。如果传入请求没有有效签名，中间件会自动返回 `403` HTTP 响应：

```php
Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
})->name('unsubscribe')->middleware('signed');
```



如果你的签名 URL 不包含 URL 哈希中的域名，则应该向中间件提供 `relative` 参数：

```php
Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
})->name('unsubscribe')->middleware('signed:relative');
```

#### 响应无效签名路由

当有人访问已经过期的签名 URL 时，他们将收到一个针对 `403` HTTP 状态码的通用错误页面。不过，你可以通过在应用程序的 `bootstrap/app.php` 文件中为 `InvalidSignatureException` 异常定义自定义的 "render" 闭包来定制此行为：

```php
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
use App\Http\Controllers\HomeController;

$url = action([HomeController::class, 'index']);
```

如果控制器方法接受路由参数，可以将包含路由参数的关联数组作为函数的第二个参数传递：

```php
$url = action([UserController::class, 'profile'], ['id' => 1]);
```

## 流式 URI 对象

Laravel 的 `Uri` 类通过对象提供了一种方便且流畅的接口，用于创建和操作 URI。该类封装了底层 League URI 包提供的功能，并与 Laravel 的路由系统无缝集成。

你可以通过静态方法轻松创建一个 `Uri` 实例：

```php
use App\Http\Controllers\UserController;
use App\Http\Controllers\InvokableController;
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']);
$uri = Uri::action(InvokableController::class);

// 根据当前请求 URL 生成 URI 实例...
$uri = $request->uri();

// 根据之前请求 URL 生成 URI 实例...
$uri = $request->session()->previousUri();
```



一旦你拥有一个 `Uri` 实例，就可以使用流式方式对其进行修改：

```php
$uri = Uri::of('https://example.com')
    ->withScheme('http')
    ->withHost('test.com')
    ->withPort(8000)
    ->withPath('/users')
    ->withQuery(['page' => 2])
    ->withFragment('section-1');
```

有关使用流式 URI 对象的更多信息，请查阅 [URI 文档](/docs/laravel/13.x/helpers#uri)。

## 默认值

对于某些应用程序，你可能希望为某些 URL 参数指定请求范围内的默认值。例如，假设你的许多路由都定义了一个 `{locale}` 参数：

```php
Route::get('/{locale}/posts', function () {
    // ...
})->name('post.index');
```

每次调用 `route` 辅助函数时都传递 `locale` 参数会比较繁琐。因此，你可以使用 `URL::defaults` 方法为该参数定义一个默认值，该值会始终在当前请求期间被应用。你可能希望从[路由中间件](/docs/laravel/13.x/middleware#assigning-middleware-to-routes)中调用此方法，以便能够访问当前请求：

```php
<?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 时，就不再需要传递该参数的值。

#### URL 默认值与中间件优先级

设置 URL 默认值可能会干扰 Laravel 对隐式模型绑定的处理。因此，你应该[调整设置 URL 默认值的中间件优先级](/docs/laravel/13.x/middleware#sorting-middleware)，使其在 Laravel 自身的 `SubstituteBindings` 中间件之前执行。你可以通过应用程序 `bootstrap/app.php` 文件中的 `priority` 中间件方法来实现：

```php
->withMiddleware(function (Middleware $middleware): void {
    $middleware->prependToPriorityList(
        before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
        prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
    );
})
```

