介绍

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

基础

生成 URL

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

  1. $post = App\Models\Post::find(1);
  2. echo url("/posts/{$post->id}");
  3. // http://example.com/posts/1

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

  1. echo url()->query('/posts', ['search' => 'Laravel']);
  2. // https://example.com/posts?search=Laravel
  3. echo url()->query('/posts?sort=latest', ['search' => 'Laravel']);
  4. // http://example.com/posts?sort=latest&search=Laravel

提供路径中已存在的查询字符串参数将覆盖其现有值:

  1. echo url()->query('/posts?sort=latest', ['sort' => 'oldest']);
  2. // http://example.com/posts?sort=oldest

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

  1. echo $url = url()->query('/posts', ['columns' => ['title', 'body']]);
  2. // http://example.com/posts?columns%5B0%5D=title&columns%5B1%5D=body
  3. echo urldecode($url);
  4. // http://example.com/posts?columns[0]=title&columns[1]=body

访问当前 URL

如果没有向 php url 助手提供路径,则返回一个 php Illuminate\Routing\UrlGenerator 实例,允许你访问当前 URL 的信息:

  1. // 获取当前不包含查询字符串的 URL...
  2. echo url()->current();
  3. // 获取当前包含查询字符串的 URL...
  4. echo url()->full();
  5. // 获取上一次请求的完整 URL...
  6. echo url()->previous();

这些方法也可以通过 php URL facade访问:

  1. use Illuminate\Support\Facades\URL;
  2. echo URL::current();

命名路由 URL

可以使用 php route 助手生成 命名路由 的 URL。命名路由允许你在不依赖于路由上实际定义的 URL 的情况下生成 URL。因此,如果路由的 URL 发生变化,不需要对 php route 函数的调用进行任何更改。例如,假设你的应用程序包含如下定义的路由:

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

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

  1. echo route('post.show', ['post' => 1]);
  2. // http://example.com/post/1

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

  1. Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) {
  2. // ...
  3. })->name('comment.show');
  4. echo route('comment.show', ['post' => 1, 'comment' => 3]);
  5. // http://example.com/post/1/comment/3

任何不对应于路由定义参数的额外数组元素都将被添加到 URL 的查询字符串中:

  1. echo route('post.show', ['post' => 1, 'search' => 'rocket']);
  2. // http://example.com/post/1?search=rocket

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

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

签名 URL

Laravel 允许你轻松创建命名路由的「签名」 URL。这些 URL 有一个附加在查询字符串上的「签名」散列,允许 Laravel 验证自创建 URL 以来 URL 未被修改。签名 URL 特别适用于那些公开可访问但需要保护以防止 URL 操纵的路由。

例如,你可能会使用签名 URL 实现公开的「取消订阅」链接,通过邮件发送给你的客户。要创建到命名路由的签名 URL,请使用 php URL facade 的 php signedRoute 方法:

  1. use Illuminate\Support\Facades\URL;
  2. return URL::signedRoute('unsubscribe', ['user' => 1]);

你可以向 php signedRoute 方法提供 php absolute 参数来排除签名 URL 散列中的域名:

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

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

  1. use Illuminate\Support\Facades\URL;
  2. return URL::temporarySignedRoute(
  3. 'unsubscribe', now()->addMinutes(30), ['user' => 1]
  4. );

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

  1. use Illuminate\Http\Request;
  2. Route::get('/unsubscribe/{user}', function (Request $request) {
  3. if (! $request->hasValidSignature()) {
  4. abort(401);
  5. }
  6. // ...
  7. })->name('unsubscribe');

有时,你可能需要允许应用程序的前端向签名 URL 追加数据,例如在客户端分页时执行此操作。因此,你可以使用 php hasValidSignatureWhileIgnoring 方法指定在验证签名 URL 时应该忽略的请求查询参数。请记住,忽略参数允许任何人修改请求上的这些参数:

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

你可以将 php signedphp Illuminate\Routing\Middleware\ValidateSignature)中间件 分配给路由,而不是使用传入请求实例验证签名 URL。如果传入请求没有有效的签名,中间件将自动返回 php 403 HTTP 响应:

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

如果你的签名 URL 不包含 URL 散列中的域名,则应对中间件提供 php relative 参数:

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

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

  1. use Illuminate\Routing\Exceptions\InvalidSignatureException;
  2. ->withExceptions(function (Exceptions $exceptions) {
  3. $exceptions->render(function (InvalidSignatureException $e) {
  4. return response()->view('error.link-expired', [], 403);
  5. });
  6. })

控制器行为的 URL

php action 功能可以为给定的控制器行为生成 URL:

  1. use App\Http\Controllers\HomeController;
  2. $url = action([HomeController::class, 'index']);

如果控制器方法接收路由参数,你可以通过第二个参数传递:

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

默认值

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

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

每次都通过 php locale 来调用辅助函数 php route 也是一件很麻烦的事情。因此,使用 php URL::defaults 方法定义这个参数的默认值,可以让该参数始终存在当前请求中。然后就能从 路由中间件 调用此方法来访问当前请求:

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\URL;
  6. use Symfony\Component\HttpFoundation\Response;
  7. class SetDefaultLocaleForUrls
  8. {
  9. /**
  10. * 处理传入的请求
  11. *
  12. * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
  13. */
  14. public function handle(Request $request, Closure $next): Response
  15. {
  16. URL::defaults(['locale' => $request->user()->locale]);
  17. return $next($request);
  18. }
  19. }

一旦设置了 php locale 参数的默认值,你就不再需要通过辅助函数 php route 生成 URL 时传递它的值。

默认 URL & 中间件优先级
设置 URL 默认值可能会干扰 Laravel 的隐式模型绑定处理。因此,你应该优先执行设置 URL 默认值的中间件,确保它们在 Laravel 自己的 php SubstituteBindings 中间件之前被执行。你可以使用应用程序 php bootstrap/app.php 文件中的 php priority 中间件方法来完成这一点:

  1. ->withMiddleware(function (Middleware $middleware) {
  2. $middleware->priority([
  3. \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
  4. \Illuminate\Cookie\Middleware\EncryptCookies::class,
  5. \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
  6. \Illuminate\Session\Middleware\StartSession::class,
  7. \Illuminate\View\Middleware\ShareErrorsFromSession::class,
  8. \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
  9. \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
  10. \Illuminate\Routing\Middleware\ThrottleRequests::class,
  11. \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
  12. \Illuminate\Session\Middleware\AuthenticateSession::class,
  13. \App\Http\Middleware\SetDefaultLocaleForUrls::class, // [tl! add]
  14. \Illuminate\Routing\Middleware\SubstituteBindings::class,
  15. \Illuminate\Auth\Middleware\Authorize::class,
  16. ]);
  17. })