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 门面来调用:

use Illuminate\Support\Facades\URL;

echo URL::current();

访问上一个 URL

有时候你需要知道用户是从哪个页面过来的。可以通过 url() 辅助函数的 previous() 和 previousPath() 方法获取上一个 URL:

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

// 获取上一个请求的路径...
echo url()->previousPath();

或者通过会话获取上一个 URL,返回的是一个流式 URI 实例:

use Illuminate\Http\Request;

Route::post('/users', function (Request $request) {
    $previousUri = $request->session()->previousUri();

    // ...
});

还可以通过会话获取上一个访问 URL 对应的路由名称:

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

命名路由的 URL

route() 辅助函数可以为命名路由生成 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 模型

生成 URL 时经常要用到 Eloquent 模型的路由键(通常是主键)。所以你可以直接把 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 参数:

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

如果你想生成一个有时效的签名 URL——过了指定时间就失效——可以用 temporarySignedRoute() 方法。Laravel 验证临时签名 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() 方法指定验证签名时要忽略哪些查询参数。注意,被忽略的参数任何人都可以随意修改:

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 没有把域名包含在哈希中,需要给中间件传 relative 参数:

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

处理无效签名路由

当有人访问一个已过期的签名 URL 时,会收到一个通用的 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,
    );
})