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=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
如果未向 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();
也可以透過 URL 門面(facade) 訪問這些方法中的每一個。
1use Illuminate\Support\Facades\URL;2 3echo URL::current();
訪問上一個 URL
有時,瞭解使用者訪問的上一頁 URL 會很有幫助。您可以透過 url 輔助函式的 previous 和 previousPath 方法訪問上一個 URL。
1// Get the full URL for the previous request...2echo url()->previous();3 4// Get the path for the previous request...5echo url()->previousPath();
或者,透過 會話(session),您可以以 流式 URI 例項的形式訪問上一個 URL。
1use Illuminate\Http\Request;2 3Route::post('/users', function (Request $request) {4 $previousUri = $request->session()->previousUri();5 6 // ...7});
也可以透過會話檢索之前訪問過的 URL 的路由名稱。
1$previousRoute = $request->session()->previousRoute();
命名路由的 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]);
簽名 URL
Laravel 允許您輕鬆建立指向命名路由的“簽名”URL。這些 URL 在查詢字串後附加了“簽名”雜湊,允許 Laravel 驗證 URL 自建立以來是否被篡改。簽名 URL 對於那些公開可訪問但需要一層防止 URL 篡改保護的路由特別有用。
例如,您可以使用簽名 URL 來實現透過電子郵件傳送給客戶的公開“取消訂閱”連結。要建立指向命名路由的簽名 URL,請使用 URL 門面的 signedRoute 方法。
1use Illuminate\Support\Facades\URL;2 3return URL::signedRoute('unsubscribe', ['user' => 1]);
您可以透過向 signedRoute 方法提供 absolute 引數,從簽名 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()->plus(minutes: 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}
您可以不用傳入請求例項來驗證簽名 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 時,他們會收到一個 403 HTTP 狀態碼的通用錯誤頁面。但是,您可以透過在應用程式的 bootstrap/app.php 檔案中為 InvalidSignatureException 異常定義自定義的“渲染”閉包來定製此行為。
1use Illuminate\Routing\Exceptions\InvalidSignatureException;2 3->withExceptions(function (Exceptions $exceptions): void {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()->plus(minutes: 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();18 19// Generate a URI instance from the previous request URL...20$uri = $request->session()->previousUri();
一旦擁有了 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');
每次呼叫 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 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 輔助函式生成 URL 時,就不再需要傳遞其值了。
URL 預設值與中介軟體優先順序
設定 URL 預設值可能會干擾 Laravel 對隱式模型繫結的處理。因此,您應該 對中介軟體進行排序,確保設定 URL 預設值的中介軟體在 Laravel 自帶的 SubstituteBindings 中介軟體之前執行。您可以在應用程式的 bootstrap/app.php 檔案中使用 priority 中介軟體方法來實現這一點。
1->withMiddleware(function (Middleware $middleware): void {2 $middleware->prependToPriorityList(3 before: \Illuminate\Routing\Middleware\SubstituteBindings::class,4 prepend: \App\Http\Middleware\SetDefaultLocaleForUrls::class,5 );6})