Skip to content

URL 生成

介绍

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,您可以使用查询方法:

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...
    echo url()->previous();

这些方法中的每一种也可以通过 URLfacade访问:

php
    use Illuminate\Support\Facades\URL;

    echo URL::current();

命名路由的 URL

路由帮助程序可用于生成命名路由的 URL。命名路由允许您生成 URL,而无需与路由上定义的实际 URL 耦合。因此,如果路由的 URL 发生变化,则无需更改对 route 函数的调用。例如,假设您的应用程序包含一个定义如下的路由:

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

要生成此路由的 URL,您可以使用路由助手,如下所示:

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

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

当然,路由帮助程序也可以用于为具有多个参数的路由生成 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 模型的路由键(通常是主键)生成 URL。因此,您可以将 Eloquent 模型作为参数值传递。route helper 会自动提取模型的 route key:

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

签名 URL

Laravel 允许您轻松创建命名路由的“签名”URL。这些 URL 在查询字符串后附加了一个“签名”哈希,允许 Laravel 验证 URL 自创建以来是否未被修改。签名 URL 对于可公开访问但需要防止 URL 操纵的保护层的路由特别有用。

例如,您可以使用签名 URL 来实现通过电子邮件发送给客户的公共“取消订阅”链接。要创建指向命名路由的签名 URL,请使用 URL Facade的 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,该 URL 在指定时间后过期,您可以使用 temporarySignedRoute 方法。当 Laravel 验证临时签名路由 URL 时,它将确保编码到签名 URL 中的过期时间戳尚未过期:

php
    use Illuminate\Support\Facades\URL;

    return URL::temporarySignedRoute(
        'unsubscribe', now()->addMinutes(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);
    }

你可以将已签名的 ( Illuminate\Routing\Middleware\ValidateSignature中间件分配给路由,而不是使用传入的请求实例来验证已签名的 URL。如果传入请求没有有效的签名,中间件将自动返回 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) {
        $exceptions->render(function (InvalidSignatureException $e) {
            return response()->view('errors.link-expired', status: 403);
        });
    })

控制器操作的 URL

action 函数为给定的控制器 action 生成一个 URL:

php
    use App\Http\Controllers\HomeController;

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

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

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

默认值

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

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

每次调用 route helper 时总是传递 locale 是很麻烦的。因此,您可以使用 URL::d efaults 方法定义此参数的默认值,该值将始终在当前请求期间应用。您可能希望从路由中间件调用此方法,以便您可以访问当前请求:

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 默认值设置为 Laravel 自己的 SubstituteBindings 中间件之前执行的中间件。您可以使用应用程序的 bootstrap/app.php 文件中的 priority 中间件方法来实现这一点:

php
->withMiddleware(function (Middleware $middleware) {
    $middleware->priority([
        \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
        \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \App\Http\Middleware\SetDefaultLocaleForUrls::class, // [tl! add]
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ]);
})