URL 生成

介绍

Laravel 提供了几个助手函数来帮助您生成应用程序的 URL。这些助手函数在构建模板和 API 响应中的链接,或者在生成重定向响应到应用程序的其它部分时非常有用。

基础知识

生成 URL

url 助手可以用来为您的应用程序生成任意的 URL。生成的 URL 将自动使用当前请求的协议(HTTP 或 HTTPS)和主机:

$post = App\Models\Post::find(1);

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

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

要生成带有查询字符串参数的 URL,您可以使用 query 方法:

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

提供已经存在于路径中的查询字符串参数时,它们的值将被覆盖:

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

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

也可以将数组作为查询参数传递。这些值将在生成的 URL 中正确地键入并进行编码:

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 的信息:

// 获取当前 URL(不包括查询字符串)...
echo url()->current();

// 获取当前 URL(包括查询字符串)...
echo url()->full();

// 获取上一请求的完整 URL...
echo url()->previous();

每个方法也可以通过 URL facade 来访问:

use Illuminate\Support\Facades\URL;

echo URL::current();

命名路由的 URL

route 助手可用于生成指向【命名路由】的 URL。命名路由使您能够生成 URL,而无需绑定到路由上实际定义的 URL。因此,如果路由的 URL 更改,您不需要更改对 route 函数的调用。例如,假设您的应用程序包含以下定义的路由:

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

要生成指向此路由的 URL,您可以像这样使用 route 助手:

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

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

当然,route 助手也可以用于生成带有多个参数的路由的 URL:

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 的查询字符串中:

echo route('post.show', ['post' => 1, 'search' => 'rocket']);

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

Eloquent 模型

您经常会使用 Eloquent 模型的路由键(通常是主键)来生成 URL。因此,您可以将 Eloquent 模型作为参数传递。route 助手会自动提取模型的路由键:

echo route('post.show', ['post' => $post]);

签名 URL

Laravel 允许您轻松创建 “签名” URL,这些 URL 会在查询字符串中附加一个 “签名” 哈希值,Laravel 可以通过该签名验证 URL 自创建以来是否未被修改。签名 URL 特别适用于那些公开访问但需要防止 URL 被篡改的路由。

例如,您可能会使用签名 URL 实现一个公开的 “取消订阅” 链接,将其通过电子邮件发送给客户。要为命名路由创建签名 URL,可以使用 URL facade 的 signedRoute 方法:

use Illuminate\Support\Facades\URL;

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

如果希望在签名 URL 的哈希中排除域名,可以向 signedRoute 方法传递 absolute 参数:

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

如果您想生成一个临时签名路由 URL,该 URL 会在指定时间后过期,可以使用 temporarySignedRoute 方法。当 Laravel 验证一个临时签名路由 URL 时,它将确保签名 URL 中编码的过期时间戳尚未过期:

use Illuminate\Support\Facades\URL;

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

验证签名路由请求

要验证传入请求是否具有有效签名,您应在传入的 Illuminate\Http\Request 实例上调用 hasValidSignature 方法:

use Illuminate\Http\Request;

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

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

有时,您可能需要允许前端将数据附加到签名 URL,例如在进行客户端分页时。因此,您可以使用 hasValidSignatureWhileIgnoring 方法指定在验证签名 URL 时应忽略的请求查询参数。请记住,忽略参数意味着任何人都可以修改这些参数:

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

除了通过传入的请求实例验证签名 URL,您还可以将签名验证中间件 (Illuminate\Routing\Middleware\ValidateSignature) 分配给路由。如果传入请求没有有效签名,该中间件会自动返回 403 HTTP 响应:

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

如果您的签名 URL 中不包括域名的 URL 哈希,您应该向中间件提供 relative 参数:

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

响应无效签名路由

当有人访问已过期的签名 URL 时,他们将收到一个通用的错误页面,显示 403 HTTP 状态码。然而,您可以通过在应用程序的 bootstrap/app.php 文件中为 InvalidSignatureException 异常定义自定义的 “渲染” 闭包来定制这一行为:

use Illuminate\Routing\Exceptions\InvalidSignatureException;

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

控制器操作的 URL

action 函数用于为给定的控制器方法生成 URL:

use App\Http\Controllers\HomeController;

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

如果控制器方法接受路由参数,您可以将一个关联数组作为第二个参数传递给该函数:

$url = action([UserController::class, 'profile'], ['id' => 1]);

默认值

对于某些应用程序,您可能希望为特定的 URL 参数指定请求范围内的默认值。例如,假设您的许多路由定义了一个 {locale} 参数:

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

每次调用 route 助手时都传递 locale 参数是很麻烦的。因此,您可以使用 URL::defaults 方法为该参数定义一个默认值,该默认值将在当前请求中始终应用。您可以在【路由中间件】中调用此方法,以便访问当前请求:

<?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 默认值的中间件优先执行,确保它在 Laravel 的 SubstituteBindings 中间件之前执行。您可以在应用程序的 bootstrap/app.php 文件中使用 priority middleware 方法来实现这一点:

->withMiddleware(function (Middleware $middleware) {
    $middleware->prependToPriorityList(
        before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
        prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
    );
})