简介
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 的相关信息:
// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();也可以通过 URL facade 来调用这些方法:
use Illuminate\Support\Facades\URL;
echo URL::current();获取上一个 URL
有时了解用户跳转前访问的上一个 URL 会很有用。你可以通过 url 辅助函数的 previous 和 previousPath 方法获取上一个 URL:
// Get the full URL for the previous request...
echo url()->previous();
// Get the path for the previous request...
echo url()->previousPath();另外,也可以通过 session,以流式 URI 实例的形式获取上一个 URL:
use Illuminate\Http\Request;
Route::post('/users', function (Request $request) {
$previousUri = $request->session()->previousUri();
// ...
});还可以通过 session 获取上一个访问 URL 的路由名称:
$previousRoute = $request->session()->previousRoute();命名路由的 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=rocketEloquent 模型
你通常会使用 Eloquent 模型的路由键(通常是主键)来生成 URL。为此,你可以将 Eloquent 模型作为参数值传入。route 辅助函数会自动提取模型的路由键:
echo route('post.show', ['post' => $post]);签名 URL
Laravel 允许你轻松为命名路由创建“签名” URL。这类 URL 会在查询字符串后追加一个“签名”哈希,Laravel 可借此验证该 URL 自生成后是否被篡改。签名 URL 对于公开可访问、但需要防范 URL 被篡改的路由尤为实用。
例如,你可以使用签名 URL 实现一个通过邮件发送给客户的公开“退订”链接。要为命名路由创建签名 URL,可使用 URL 门面的 signedRoute 方法:
use Illuminate\Support\Facades\URL;
return URL::signedRoute('unsubscribe', ['user' => 1]);通过向 signedRoute 方法传入 absolute 参数,可让签名 URL 的哈希中不包含域名:
return URL::signedRoute('unsubscribe', ['user' => 1], absolute: false);如果你想生成一个在指定时长后失效的临时签名路由 URL,可以使用 temporarySignedRoute 方法。当 Laravel 验证临时签名路由 URL 时,会确保编码在签名 URL 中的过期时间戳尚未失效:
use Illuminate\Support\Facades\URL;
return URL::temporarySignedRoute(
'unsubscribe', now()->plus(minutes: 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,还可以为路由指定 signed(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 的路径和查询字符串。其他任何请求输入(如表单或 JSON 请求体)都未签名,用户可自由修改。由于 Laravel 会将这些输入源合并,且请求体的优先级高于查询字符串,因此使用除 query 以外的任何方法获取输入(如 input、all 或动态请求属性),可能会返回未签名的值,从而覆盖已签名的查询字符串值。因此,应始终使用 query 方法获取签名值,例如 $request->query('email')。这同样适用于 GET 请求,因为精心构造的 GET 请求也可能包含 JSON 请求体。
响应无效的签名路由
当有人访问已过期的签名 URL 时,会收到 HTTP 状态码 403 的通用错误页面。不过,你可以在应用程序的 bootstrap/app.php 文件中,为 InvalidSignatureException 异常定义自定义的“渲染”闭包,从而自定义该行为:
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:
use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);如果控制器方法需要接收路由参数,你可以将包含路由参数的关联数组作为该函数的第二个参数传入:
$url = action([UserController::class, 'profile'], ['id' => 1]);流畅的 URI 对象
Laravel 的 Uri 类提供了便捷且流畅的接口,可通过对象创建和操作 URI。该类封装了底层 League URI 包提供的功能,并与 Laravel 的路由系统无缝集成。
你可以使用静态方法轻松创建 Uri 实例:
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 实例后,你可以流畅地对其进行修改:
$uri = Uri::of('https://example.com')
->withScheme('http')
->withHost('test.com')
->withPort(8000)
->withPath('/users')
->withQuery(['page' => 2])
->withFragment('section-1');若想进一步了解流畅 URI 对象的使用,请参阅URI 文档。
默认值
在某些应用中,你可能需要为特定 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 中间件方法实现这一点:
->withMiddleware(function (Middleware $middleware): void {
$middleware->prependToPriorityList(
before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
);
})