Laravel 11.35.0: Introducing the URI Class
Introducing the Uri Class in Laravel 11.35.0
Laravel 11.35.0 introduces a fantastic new feature: the Uri class, contributed by Taylor Otwell. This new addition makes working with URIs (Uniform Resource Identifiers) in Laravel applications easier and more expressive.
What is the Uri Class?
The Uri class provides methods for handling and manipulating URIs. It allows developers to extract components such as schemes, hosts, paths, queries, and ports more cleanly and conveniently.
Here’s how you can use it:
Usage Examples
-
Creating URI instances with
Uri::of
$uri = Uri::of('https://laravel.com') ->withQuery(['name' => 'Taylor']) ->withPath('/docs/installation') ->withFragment('hello-world'); // some of the available methods$uri->scheme();$uri->host();$uri->user();$uri->password();$uri->path();$uri->port();$uri->query()->all();$uri->query()->has('name');$uri->query()->missing('name');$uri->query()->decode();(string) $uri;
- Retrieve URI instance from the current request
$uri = $request->uri();
- Retrieve absolute URL for a path
// will append "/something" to your app's base url and returns an absolute URL$uri = Uri::to('/something')->withQuery(...);
- URI with named routes
$uri = Uri::route('named-route', ['user' => $user]); // generates a redirect to the locationreturn Uri::route('named-route', ['user' => $user])->withQuery(['name' => 'Taylor']);
Conclusion
Before this release, developers often relied on PHP's native parse_url function, which could be cumbersome and error-prone. The new Uri class in Laravel provides an elegant and developer-friendly API for these tasks, ensuring better readability and maintainability. For more detail about this feature, check out pull request #53731.
Stay Updated.
I'll you email you as soon as new, fresh content is published.