Laravel 11.35 引入了基於 PHP League URI 庫的 Uri
類。 Uri
簡化了在 Laravel 應用中操作和處理 URI 的過程,並提供了一些關於命名路由的便利功能。
基本操作
Uri
類的核心功能是創建和操作 URI 字符串,包括查詢、片段和路徑:
use Illuminate\Support\Uri; $uri = Uri::of('https://laravel-news.com') ->withPath('links') ->withQuery(['page' => 2]) ->withFragment('new'); (string) $url; // https://laravel-news.com/links?page=2#new $uri->path(); // links $uri->scheme(); // https $uri->port(); // null $uri->host(); // laravel-news.com
請注意獲取 URI 值和解碼 URI 之間的區別:
查詢斷言和操作
在 Laravel 中,使用底層的 UriQueryString
來斷言和操作 URI 查詢參數從未如此簡單。 UriQueryString
類使用支持特性 InteractsWithData
,它為你提供了一堆用於斷言查詢字符串的有用方法:
use Illuminate\Support\Uri; $uri = Uri::of("https://laravel-news.com") ->withPath("links") ->withQuery(["page" => 2, 'name' => '']) ->withFragment("new"); $uri->query()->all(); // ["page" => "2"] $uri->query()->hasAny("page", "limit"); // true $uri->query()->has("name"); // true $uri->query()->has('limit'); // false $uri->query()->missing('limit'); // true $uri->query()->filled('page'); // true $uri->query()->filled("name"); // false $uri->query()->isNotFilled("name"); // true $uri->query()->isNotFilled("page"); // false $uri->query()->string("page", "1"); // Stringable{ value: 2 } $uri->query()->integer("limit", 10); // 10
了解 InteractsWithData
為 UriQueryString
實例提供的用於斷言和操作查詢數據的所有有用方法。
從命名路由、路徑和當前請求獲取 Uri 實例
Uri
類還可以從應用程序中的命名路由、相對 URL 甚至當前 Request
實例創建 URI:
// 使用命名路由 (string) Uri::route("dashboard"); // http://laravel.test/dashboard // 使用根相对 URL (string) Uri::to("/dashboard"); // http://laravel.test/dashboard // 从当前请求 function (Request $request) { (string) $request->uri(); // http://laravel.test/dashboard }
從 Laravel 11.36 開始,Uri
類在 Laravel 應用程序中默認別名化,這意味著您可以無需導入 IlluminateSupportUri
命名空間即可使用它。
了解更多
我們希望您在 Laravel 應用程序中享受使用 Uri
的樂趣! Uri
類在 Laravel 11.35 的 #53731 中發布。此外,請閱讀有關 InteractsWithData
的信息,它提供了許多用於處理 Uri
類、Fluent 類和 Laravel 的 HTTP 請求類(通過 InteractsWithInput
)的有用方法。
以上是與烏里斯(Uris)合作的詳細內容。更多資訊請關注PHP中文網其他相關文章!