跳到內容

URL 產生

簡介

Laravel 提供了數個輔助函式來協助您為應用程式產生 URL。當您在範本和 API 回應中建立連結,或在產生重新導向回應到應用程式的另一個部分時,這些輔助函式特別有用。

基礎

產生 URL

url 輔助函式可用於為您的應用程式產生任意 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=Laravel
4 
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=body
4 
5echo urldecode($url);
6 
7// http://example.com/posts?columns[0]=title&columns[1]=body

存取目前的 URL

如果沒有為 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 facade 存取。

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

具名路由的 URL

route 輔助函式可用於產生指向具名路由的 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 輔助函式也可用於產生具有多個參數的路由的 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 輔助函式將自動提取模型的路由鍵。

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

簽名網址

Laravel 允許您輕鬆建立指向具名路由的「簽名」URL。這些 URL 在查詢字串中附加了「簽名」雜湊,讓 Laravel 可以驗證 URL 自建立以來是否未被修改。簽名 URL 對於公開存取但需要一層保護以防止 URL 操縱的路徑特別有用。

例如,您可以使用簽名 URL 來實作電子郵件發送給客戶的公開「取消訂閱」連結。若要建立指向具名路由的簽名 URL,請使用 URL facade 的 signedRoute 方法。

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

您可以透過提供 absolute 引數給 signedRoute 方法,從簽名 URL 雜湊中排除網域。

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);

驗證簽名路由請求

若要驗證傳入的請求是否具有有效的簽名,您應該在傳入的 Illuminate\Http\Request 實例上呼叫 hasValidSignature 方法。

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}

您可以使用指派給路由的 signed (Illuminate\Routing\Middleware\ValidateSignature) 中介層,而不是使用傳入的請求實例驗證簽名 URL。如果傳入的請求沒有有效的簽名,中介層將自動傳回 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 時,他們將收到 403 HTTP 狀態碼的通用錯誤頁面。但是,您可以透過在應用程式的 bootstrap/app.php 檔案中為 InvalidSignatureException 例外定義自訂「render」閉包來自訂此行為。

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]);

預設值

對於某些應用程式,您可能希望為某些 URL 參數指定請求範圍的預設值。例如,假設您的許多路由都定義了 {locale} 參數。

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

每次呼叫 route 輔助函式時都始終傳遞 locale 是很麻煩的。因此,您可以使用 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 SetDefaultLocaleForUrls
11{
12 /**
13 * Handle an incoming request.
14 *
15 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
16 */
17 public function handle(Request $request, Closure $next): Response
18 {
19 URL::defaults(['locale' => $request->user()->locale]);
20 
21 return $next($request);
22 }
23}

一旦設定了 locale 參數的預設值,您在透過 route 輔助函式產生 URL 時就不再需要傳遞其值。

URL 預設值和中介層優先順序

設定 URL 預設值可能會干擾 Laravel 處理隱式模型綁定的方式。因此,您應該優先處理您的中介層,這些中介層設定 URL 預設值,以便在 Laravel 自己的 SubstituteBindings 中介層之前執行。您可以使用應用程式 bootstrap/app.php 檔案中的 priority 中介層方法來完成此操作。

1->withMiddleware(function (Middleware $middleware) {
2 $middleware->prependToPriorityList(
3 before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
4 prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,
5 );
6})