URL 生成
介绍
Laravel 提供了一些Helpers函数来帮助你为应用程序生成 URL。这些Helpers函数主要在模板和 API 响应中构建链接,或者生成指向应用程序其他部分的重定向响应时有用。
基础知识
生成 URL
该url
Helpers可用于为你的应用程序生成任意 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=Laravel4 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=body4 5echo urldecode($url);6 7// http://example.com/posts?columns[0]=title&columns[1]=body
访问当前 URL
如果没有向Helpers提供路径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(); 6 7// Get the full URL for the previous request... 8echo url()->previous(); 9 10// Get the path for the previous request...11echo url()->previousPath();
这些方法也可以通过URL
外观来访问:
1use Illuminate\Support\Facades\URL;2 3echo URL::current();
命名路由的 URL
该route
Helpers可用于生成指向命名路由的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
Helpers也可以用于为具有多个参数的路由生成 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
Helpers会自动提取模型的路由键:
1echo route('post.show', ['post' => $post]);
签名 URL
Laravel 允许您轻松地为命名路由创建“签名” URL。这些 URL 在查询字符串后附加一个“签名”哈希值,以便 Laravel 验证 URL 自创建以来未被修改过。签名 URL 对于那些可公开访问但需要一层保护以防止 URL 篡改的路由尤其有用。
例如,您可以使用签名 URL 来实现一个公开的“取消订阅”链接,并通过电子邮件发送给您的客户。要创建指向命名路由的签名 URL,请使用FacadesignedRoute
的以下方法URL
:
1use Illuminate\Support\Facades\URL;2 3return URL::signedRoute('unsubscribe', ['user' => 1]);
absolute
您可以通过向方法提供参数来从签名的 URL 哈希中排除域signedRoute
:
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()->addMinutes(30), ['user' => 1]5);
验证签名的路由请求
要验证传入请求是否具有有效签名,您应该hasValidSignature
在传入Illuminate\Http\Request
实例上调用该方法:
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 时,他们会收到一个包含 HTTP 状态码的通用错误页面。不过,你可以在应用文件中403
为异常定义一个自定义的“render”闭包来自定义此行为:InvalidSignatureException
bootstrap/app.php
1use Illuminate\Routing\Exceptions\InvalidSignatureException;2 3->withExceptions(function (Exceptions $exceptions) {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()->addMinutes(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();
一旦有了 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');
locale
每次调用辅助函数时都传递参数会很麻烦route
。因此,您可以使用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 SetDefaultLocaleForUrls11{12 /**13 * Handle an incoming request.14 *15 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next16 */17 public function handle(Request $request, Closure $next): Response18 {19 URL::defaults(['locale' => $request->user()->locale]);20 21 return $next($request);22 }23}
一旦设置了参数的默认值locale
,您就不再需要在通过route
Helpers生成 URL 时传递其值。
URL 默认值和中间件优先级
设置 URL 默认值可能会干扰 Laravel 对隐式模型绑定的处理。因此,你应该优先执行设置 URL 默认值的中间件SubstituteBindings
,而不是 Laravel 自身的中间件。你可以priority
在应用程序bootstrap/app.php
文件中使用 middleware 方法来实现这一点:
1->withMiddleware(function (Middleware $middleware) {2 $middleware->prependToPriorityList(3 before: \Illuminate\Routing\Middleware\SubstituteBindings::class,4 prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,5 );6})