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中文网其他相关文章!