跳转至内容

URL 生成

简介

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

基础

生成 URL

url 辅助函数可用于为您的应用程序生成任意 URL。生成的 URL 将自动使用当前请求处理程序所使用的协议(HTTP 或 HTTPS)和主机名。

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

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

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

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

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

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

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

访问当前 URL

如果未向 url 辅助函数提供路径,则会返回一个 Illuminate\Routing\UrlGenerator 实例,允许您访问有关当前 URL 的信息。

1// Get the current URL without the query string...
2echo url()->current();
3 
4// Get the current URL including the query string...
5echo url()->full();

也可以通过 URL 门面(facade) 访问这些方法中的每一个。

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

访问上一个 URL

有时,了解用户访问的上一页 URL 会很有帮助。您可以通过 url 辅助函数的 previouspreviousPath 方法访问上一个 URL。

1// Get the full URL for the previous request...
2echo url()->previous();
3 
4// Get the path for the previous request...
5echo url()->previousPath();

或者,通过 会话(session),您可以以 流式 URI 实例的形式访问上一个 URL。

1use Illuminate\Http\Request;
2 
3Route::post('/users', function (Request $request) {
4 $previousUri = $request->session()->previousUri();
5 
6 // ...
7});

也可以通过会话检索之前访问过的 URL 的路由名称。

1$previousRoute = $request->session()->previousRoute();

命名路由的 URL

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

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

要为此路由生成 URL,您可以像这样使用 route 辅助函数:

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

当然,route 辅助函数也可用于为具有多个参数的路由生成 URL。

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

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

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

Eloquent 模型

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

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

签名 URL

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

例如,您可以使用签名 URL 来实现通过电子邮件发送给客户的公开“取消订阅”链接。要创建指向命名路由的签名 URL,请使用 URL 门面的 signedRoute 方法。

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

您可以通过向 signedRoute 方法提供 absolute 参数,从签名 URL 哈希中排除域名。

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

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

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

验证签名路由请求

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

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

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

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

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

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

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

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

响应无效的签名路由

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

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

控制器操作的 URL

action 函数为给定的控制器操作生成 URL。

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

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

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

流式 URI 对象

Laravel 的 Uri 类为通过对象创建和操作 URI 提供了一个方便且流式的接口。此类封装了底层 League URI 包提供的功能,并与 Laravel 的路由系统无缝集成。

您可以使用静态方法轻松创建 Uri 实例。

1use App\Http\Controllers\UserController;
2use App\Http\Controllers\InvokableController;
3use Illuminate\Support\Uri;
4 
5// Generate a URI instance from the given string...
6$uri = Uri::of('https://example.com/path');
7 
8// Generate URI instances to paths, named routes, or controller actions...
9$uri = Uri::to('/dashboard');
10$uri = Uri::route('users.show', ['user' => 1]);
11$uri = Uri::signedRoute('users.show', ['user' => 1]);
12$uri = Uri::temporarySignedRoute('user.index', now()->plus(minutes: 5));
13$uri = Uri::action([UserController::class, 'index']);
14$uri = Uri::action(InvokableController::class);
15 
16// Generate a URI instance from the current request URL...
17$uri = $request->uri();
18 
19// Generate a URI instance from the previous request URL...
20$uri = $request->session()->previousUri();

一旦拥有了 URI 实例,就可以流式地修改它。

1$uri = Uri::of('https://example.com')
2 ->withScheme('http')
3 ->withHost('test.com')
4 ->withPort(8000)
5 ->withPath('/users')
6 ->withQuery(['page' => 2])
7 ->withFragment('section-1');

有关使用流式 URI 对象的更多信息,请查阅 URI 文档

默认值

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

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

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

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

一旦设置了 locale 参数的默认值,在使用 route 辅助函数生成 URL 时,就不再需要传递其值了。

URL 默认值与中间件优先级

设置 URL 默认值可能会干扰 Laravel 对隐式模型绑定的处理。因此,您应该 对中间件进行排序,确保设置 URL 默认值的中间件在 Laravel 自带的 SubstituteBindings 中间件之前执行。您可以在应用程序的 bootstrap/app.php 文件中使用 priority 中间件方法来实现这一点。

1->withMiddleware(function (Middleware $middleware): void {
2 $middleware->prependToPriorityList(
3 before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
4 prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
5 );
6})