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,可使用 query 方法:

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
// Get the current URL without the query string...
echo url()->current();

// Get the current URL including the query string...
echo url()->full();

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

php
use Illuminate\Support\Facades\URL;

echo URL::current();

访问上一页 URL

有时需要知道用户来自哪个上一页 URL。可通过 url 辅助函数的 previouspreviousPath 方法访问:

php
// Get the full URL for the previous request...
echo url()->previous();

// Get the path for the previous request...
echo url()->previousPath();

或者,可通过 session 将上一页 URL 作为流式 URI 实例访问:

php
use Illuminate\Http\Request;

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

    // ...
});

也可以通过 session 获取上一页 URL 对应的路由名称:

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

命名路由的 URL

route 辅助函数可用于生成指向命名路由的 URL。命名路由让你在生成 URL 时不必耦合到路由上定义的实际路径。因此,若路由 URL 发生变化,无需修改对 route 函数的调用。例如,假设应用中有如下路由定义:

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

要生成该路由的 URL,可像这样使用 route 辅助函数:

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

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

当然,route 辅助函数也可用于生成带多个参数的路由 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 辅助函数会自动提取模型的路由键:

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,可使用 temporarySignedRoute 方法。Laravel 验证临时签名路由 URL 时,会确保编码在签名 URL 中的过期时间戳尚未过期:

php
use Illuminate\Support\Facades\URL;

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

除了用传入请求实例验证签名 URL,也可将 signedIlluminate\Routing\Middleware\ValidateSignature中间件分配给路由。若传入请求没有有效签名,中间件会自动返回 403 HTTP 响应:

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

若签名 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): void {
    $exceptions->render(function (InvalidSignatureException $e) {
        return response()->view('errors.link-expired', status: 403);
    });
})

控制器动作的 URL

action 函数可为给定控制器动作生成 URL:

php
use App\Http\Controllers\HomeController;

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

若控制器方法接受路由参数,可将路由参数的关联数组作为函数的第二个参数传入:

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

流式 URI 对象

Laravel 的 Uri 类提供了便捷的流式接口,用于通过对象创建与操作 URI。该类封装了底层 League URI 包提供的功能,并与 Laravel 的路由系统无缝集成。

可使用静态方法轻松创建 Uri 实例:

php
use App\Http\Controllers\UserController;
use App\Http\Controllers\InvokableController;
use Illuminate\Support\Uri;

// Generate a URI instance from the given string...
$uri = Uri::of('https://example.com/path');

// Generate URI instances to paths, named routes, or controller actions...
$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);

// Generate a URI instance from the current request URL...
$uri = $request->uri();

// Generate a URI instance from the previous request URL...
$uri = $request->session()->previousUri();

获得 URI 实例后,可流式地修改它:

php
$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} 参数:

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

每次调用 route 辅助函数都传入 locale 会很繁琐。因此,可使用 URL::defaults 方法为该参数定义默认值,并在当前请求期间始终应用。你可能希望在路由中间件中调用此方法,以便访问当前请求:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;

class SetDefaultLocaleForUrls
{
    /**
     * Handle an incoming request.
     *
     * @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): void {
    $middleware->prependToPriorityList(
        before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
        prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
    );
})