跳至內容

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 的資訊

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

也可以透過 URL facade 存取這些方法中的每一個

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

具名路由的 URL

可以使用 route 輔助函數產生指向具名路由的 URL。具名路由可讓您產生 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 模型

您通常會使用Eloquent 模型的路由鍵 (通常是主鍵) 來產生 URL。因此,您可以將 Eloquent 模型當作參數值傳遞。route 輔助函數將自動擷取模型的路由鍵

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

簽署的 URL

Laravel 可讓您輕鬆地為具名路由建立「簽署的」URL。這些 URL 在查詢字串中附加了「簽名」雜湊,可讓 Laravel 驗證自建立 URL 以來未經修改。簽署的 URL 特別適用於公開存取但需要一層保護以防範 URL 操作的路由。

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

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

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

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

如果您想要產生在指定時間後過期的暫時簽署路由 URL,您可以使用 temporarySignedRoute 方法。當 Laravel 驗證暫時簽署的路由 URL 時,將確保編碼到簽署 URL 中的到期時間戳記尚未經過

use Illuminate\Support\Facades\URL;
 
return URL::temporarySignedRoute(
'unsubscribe', now()->addMinutes(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 方法指定驗證簽署 URL 時應忽略的請求查詢參數。請記住,忽略參數允許任何人修改請求上的這些參數

if (! $request->hasValidSignatureWhileIgnoring(['page', 'order'])) {
abort(401);
}

您可以將 signed (Illuminate\Routing\Middleware\ValidateSignature) 中介層指派給路由,而非使用傳入的請求實例驗證簽署的 URL。如果傳入的請求沒有有效的簽名,中介層會自動傳回 403 HTTP 回應

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

如果您的簽署 URL 不在 URL 雜湊中包含網域,您應該將 relative 引數提供給中介層

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

回應無效的簽署路由

當有人造訪已過期的簽署 URL 時,他們會收到 403 HTTP 狀態碼的通用錯誤頁面。不過,您可以在應用程式的 bootstrap/app.php 檔案中為 InvalidSignatureException 例外狀況定義自訂的「render」閉包,藉此自訂此行為

use Illuminate\Routing\Exceptions\InvalidSignatureException;
 
->withExceptions(function (Exceptions $exceptions) {
$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]);

預設值

對於某些應用程式,您可能會想要為某些 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
{
/**
* 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 中介層方法來完成此操作

->withMiddleware(function (Middleware $middleware) {
$middleware->priority([
\Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
\Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\App\Http\Middleware\SetDefaultLocaleForUrls::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
]);
})