league/uri
League URI is a PHP 8.1+ library with intuitive classes for parsing, validating, normalizing, and manipulating URIs. Supports PSR-7 integration plus optional IDN, IPv4 conversion, and HTML/DOM features when extensions are available.
Installation:
composer require league/uri
Ensure PHP ≥ 8.1 and required extensions (intl, dom, GMP/BCMath for IPv4, or 64-bit PHP).
First Use Case: Parse and manipulate a URI:
use League\Uri\Uri;
$uri = Uri::new('https://example.com/path?query=value');
echo $uri->getHost(); // "example.com"
Key Entry Points:
Uri::new() – Parse a URI string.Uri::fromComponents() – Build from components (e.g., scheme, host, path).Http class – PSR-7 compliant HTTP URIs (e.g., Http::new('https://api.example.com')).Documentation:
Uri::new replaced createFromString in v7.0).$uri = Uri::new('https://user:pass@example.com:8080/path?query=1');
$uri = Uri::fromComponents([
'scheme' => 'https',
'host' => 'example.com',
'path' => '/api/v1',
]);
$uri = (new Uri\Builder())
->scheme('https')
->host('example.com')
->path('/api/v1')
->build();
$newUri = $uri->withPath('/new-path')->withQuery(['key' => 'value']);
$base = Uri::new('https://example.com/base/');
$relative = Uri::new('subpath');
$resolved = $base->resolve($relative); // "https://example.com/base/subpath"
$normalized = $uri->normalize(); // Decodes % encodings, compresses IPv6.
$isValid = $uri->isAbsolute(); // Checks RFC 3986 compliance.
use League\Uri\Http;
$httpUri = Http::new('https://example.com');
$psr7Uri = $httpUri->toPsr7Uri(); // Returns Psr7\UriInterface.
$isSameOrigin = $uri->isSameOrigin($anotherUri);
$isCrossOrigin = $uri->isCrossOrigin($anotherUri);
$template = UriTemplate::new('https://api.example.com/{version}/users/{id}');
$uri = $template->expand(['version' => 'v1', 'id' => '123']);
// "https://api.example.com/v1/users/123"
$base = Uri::new('https://api.example.com/');
$uri = $template->expand(['id' => '123'], $base);
$fileUri = Uri::fromUnixPath('/var/www/html/index.html');
$isLocal = $fileUri->isLocalFile(); // true
Request:
use League\Uri\Uri;
$requestUri = Uri::fromServer($_SERVER);
// Or via Laravel’s Request facade:
$uri = Uri::new(request()->getUri());
return redirect()->to($uri->toString());
$this->app->bind(UriFactoryInterface::class, function () {
return new League\Uri\HttpFactory();
});
use League\Uri\Uri;
$validator = Validator::make($data, [
'url' => ['required', function ($attribute, $value, $fail) {
if (!Uri::tryNew($value)) {
$fail('The :attribute must be a valid URI.');
}
}],
]);
Route::get('/api/{version}/users/{id}', function ($version, $id) {
$uri = UriTemplate::new('/api/{version}/users/{id}')
->expand(['version' => $version, 'id' => $id]);
return response()->json(['uri' => $uri->toString()]);
});
$job = new ProcessUri($uri->toString());
ProcessUri::dispatch($uri->toString());
public function handle() {
$uri = Uri::new($this->uri);
// Process...
}
Immutable Objects:
withPath() return new instances; original remains unchanged.$uri = $uri->withPath('/new')->withQuery(['key' => 'value']);
IDN (Internationalized Domain Names):
intl extension or symfony/polyfill-intl-idn.composer require symfony/polyfill-intl-idn
IPv4/IPv6 Handling:
GMP, BCMath, or 64-bit PHP.isIpv4Host()/isIpv6Host() to validate:
if (!$uri->isIpv6Host()) {
throw new \RuntimeException('IPv6 not supported');
}
Path Normalization:
Uri::getPath() preserves leading slashes (unlike Http class).normalize() for consistency:
$normalizedPath = $uri->normalize()->getPath();
Query String Order:
isSameDocument() compares query strings order-sensitive.ksort($uri->getQuery());
Deprecated Methods:
Uri::fromBaseUri() is deprecated (use resolve()).PSR-7 Conflicts:
Http class implements Psr7\UriInterface, but Uri does not.Http for PSR-7 contexts:
$psr7Uri = Http::new($uri->toString())->toPsr7Uri();
Fragment Handling:
equals() considers fragments; isSameDocument() ignores them.equals() for exact matches:
$uri1->equals($uri2); // true if fragments match
Validate URIs:
if (!Uri::tryNew($string)) {
throw new \InvalidArgumentException('Invalid URI');
}
Inspect Components:
dump($uri->getComponents()); // Array of all components.
Check RFC Compliance:
$uri->toAsciiString(); // RFC 3986 encoding.
$uri->toDisplayString(); // Human-readable IRI.
Handle Exceptions:
UriException for parsing errors.TemplateCanNotBeExpanded for invalid templates.tryNew() or expandOrFail() for graceful handling:
$uri = Uri::tryNew($string) ?? throw new \RuntimeException('Invalid URI');
Uri or Http for domain-specific logic:
class ApiUri extends
How can I help you explore Laravel packages today?