URL 生成


简介

Laravel 提供了多个辅助函数来帮助我们在应用中生成 URL。这些函数主要用于在视图模板和 API 响应中构建链接,或者生成重定向响应。

快速入门

生成 URL

url 辅助函数可用于为应用生成任意 URL,并且生成的 URL 会自动使用当前请求的 scheme(HTTP or HTTPS) 和 host 属性:

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

访问当前 URL

如果没有传递路径信息给 url 辅助函数,则会返回一个 Illuminate\Routing\UrlGenerator 实例,从而允许你访问当前 URL 的信息:

// 获取不带请求字符串的当前 URL...
echo url()->current();
    
// 获取包含请求字符串的当前 URL...
echo url()->full();
    
// 获取上一个请求的完整 URL...
echo url()->previous();

上述每一个方法都可以通过 URL 门面进行访问,例如:

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

命名路由 URL

route 可用于生成指向命名路由的 URL。命名路由允许你生成不与路由中定义的实际 URL 耦合的 URL,因此,当路由的 URL 改变了,route 函数调用不需要做任何更改。例如,假设你的应用包含一个定义如下的路由:

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

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

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

通常我们会使用 Eloquent 模型的主键来生成 URL,因此,可以传递 Eloquent 模型作为参数值,route 辅助函数会自动解析模型主键值,所以,上述方法还可以这么调用:

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

route 辅助函数还可以用于为包含多个参数的路由生成对应的 URL:

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

签名 URL

Laravel 允许你轻松创建与命名路由映射的「签名」URL,这些 URL 会将「签名」哈希追加到查询字符串后面,以便 Laravel 验证 URL 在创建之后没有被篡改。签名 URL 对于那些可以公开访问的路由非常有用,因为这相当于对这些 URL 的修改提供了一个保护层。

例如,你可以使用签名 URL 来实现一个公开的「退订」邮件链接,要创建这个签名 URL 对应的命名路由,可以使用 URL 门面提供的 signedRoute 方法:

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

如果你想要生成一个包含过期时间的临时签名 URL,可以使用 temporarySignedRoute 方法:

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

验证签名路由请求

要验证输入请求包含有效的签名,需要调用 Request 对象上的 hasValidSignature 方法:

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

此外,你还可以分配 Illuminate\Routing\Middleware\ValidateSignature 中间件到该路由。你可以先将这个中间件注册到 $routeMiddleware

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
];

然后将其分配到路由,如果输入请求未包含有效的签名,中间件会自动返回 403 错误响应:

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

控制器动作 URL

action 辅助函数用于为控制器动作生成 URL:

use App\Http\Controllers\HomeController;

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

如果控制器方法接收路由参数,你可以将其作为第二个参数传递给该方法:

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

参数默认值

对某些应用而言,你可能希望为特定 URL 参数指定请求默认值,例如,假设多个路由都定义了一个 {locale} 变量:

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

每次调用 route 辅助函数都要传递 locale 变量显得很笨拙,所以,我们可以在当前请求中使用 URL::defaults 方法为这个参数定义一个默认值,我们可以在某个路由中间件中调用该方法以便可以访问当前请求:

<?php
    
namespace App\Http\Middleware;
    
use Closure;
use Illuminate\Support\Facades\URL;
    
class SetDefaultLocaleForUrls
{
    public function handle($request, Closure $next)
    {
        URL::defaults(['locale' => $request->user()->locale]);
    
        return $next($request);
    }
}

一旦设置好 locale 参数的默认值之后,就不必在通过 route 辅助函数生成 URL 时每次指定传递的值了。

URL 默认值 & 中间件优先级

设置 URL 默认值可能会干扰 Laravel 对隐式模型绑定的处理。因此,你需要调整中间件的优先级,将 URL 默认值设置中间件放到 SubstituteBindings 中间件之前执行,这很简单,在 HTTP Kernel 类的 $middlewarePriority 数组属性中,确保设置 URL 默认值的中间件位于 SubstituteBindings 之前即可。

$middlewarePriority 属性定义在 Illuminate\Foundation\Http\Kernel 类中,你可以将其拷贝到子类(App\Http\Kernel)并重写该属性来完成中间件优先级设置:

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    // ...
     \App\Http\MiddlewareSetDefaultLocaleForUrls::class,
     \Illuminate\Routing\Middleware\SubstituteBindings::class,
     // ...
];

点赞 取消点赞 收藏 取消收藏

<< 上一篇: Blade 模板引擎

>> 下一篇: Session