Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Uri Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/uri
    

    Ensure PHP ≥ 8.1 and required extensions (intl, dom, GMP/BCMath for IPv4, or 64-bit PHP).

  2. 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"
    
  3. 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')).
  4. Documentation:

    • Official Docs (API reference, RFC compliance).
    • Changelog for breaking changes (e.g., Uri::new replaced createFromString in v7.0).

Implementation Patterns

Core Workflows

1. URI Construction

  • From a string:
    $uri = Uri::new('https://user:pass@example.com:8080/path?query=1');
    
  • From components (immutable):
    $uri = Uri::fromComponents([
        'scheme' => 'https',
        'host'   => 'example.com',
        'path'   => '/api/v1',
    ]);
    
  • Builder pattern (v7.8+):
    $uri = (new Uri\Builder())
        ->scheme('https')
        ->host('example.com')
        ->path('/api/v1')
        ->build();
    

2. URI Manipulation

  • Modify components (returns new instance):
    $newUri = $uri->withPath('/new-path')->withQuery(['key' => 'value']);
    
  • Resolve relative URIs:
    $base = Uri::new('https://example.com/base/');
    $relative = Uri::new('subpath');
    $resolved = $base->resolve($relative); // "https://example.com/base/subpath"
    
  • Normalize/validate:
    $normalized = $uri->normalize(); // Decodes % encodings, compresses IPv6.
    $isValid = $uri->isAbsolute();   // Checks RFC 3986 compliance.
    

3. HTTP-Specific Logic

  • PSR-7 compatibility:
    use League\Uri\Http;
    
    $httpUri = Http::new('https://example.com');
    $psr7Uri = $httpUri->toPsr7Uri(); // Returns Psr7\UriInterface.
    
  • Origin checks:
    $isSameOrigin = $uri->isSameOrigin($anotherUri);
    $isCrossOrigin = $uri->isCrossOrigin($anotherUri);
    

4. URI Templates

  • Expand variables:
    $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 resolution:
    $base = Uri::new('https://api.example.com/');
    $uri = $template->expand(['id' => '123'], $base);
    

5. File URIs

  • Local file handling:
    $fileUri = Uri::fromUnixPath('/var/www/html/index.html');
    $isLocal = $fileUri->isLocalFile(); // true
    

Laravel Integration Tips

1. Request/Response Handling

  • Extract from Laravel’s Request:
    use League\Uri\Uri;
    
    $requestUri = Uri::fromServer($_SERVER);
    // Or via Laravel’s Request facade:
    $uri = Uri::new(request()->getUri());
    
  • Generate redirects:
    return redirect()->to($uri->toString());
    

2. Service Providers

  • Bind URI factory:
    $this->app->bind(UriFactoryInterface::class, function () {
        return new League\Uri\HttpFactory();
    });
    

3. Validation

  • Form requests:
    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.');
            }
        }],
    ]);
    

4. API Routes

  • Dynamic route parameters:
    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()]);
    });
    

5. Queue Jobs

  • Serialize URIs:
    $job = new ProcessUri($uri->toString());
    ProcessUri::dispatch($uri->toString());
    
  • Job handler:
    public function handle() {
        $uri = Uri::new($this->uri);
        // Process...
    }
    

Gotchas and Tips

Pitfalls

  1. Immutable Objects:

    • Methods like withPath() return new instances; original remains unchanged.
    • Fix: Chain methods or store the result:
      $uri = $uri->withPath('/new')->withQuery(['key' => 'value']);
      
  2. IDN (Internationalized Domain Names):

    • Requires intl extension or symfony/polyfill-intl-idn.
    • Fix: Install polyfill if missing:
      composer require symfony/polyfill-intl-idn
      
  3. IPv4/IPv6 Handling:

    • IPv6 requires GMP, BCMath, or 64-bit PHP.
    • Fix: Use isIpv4Host()/isIpv6Host() to validate:
      if (!$uri->isIpv6Host()) {
          throw new \RuntimeException('IPv6 not supported');
      }
      
  4. Path Normalization:

    • Uri::getPath() preserves leading slashes (unlike Http class).
    • Fix: Use normalize() for consistency:
      $normalizedPath = $uri->normalize()->getPath();
      
  5. Query String Order:

    • isSameDocument() compares query strings order-sensitive.
    • Fix: Sort queries manually if order matters:
      ksort($uri->getQuery());
      
  6. Deprecated Methods:

    • Uri::fromBaseUri() is deprecated (use resolve()).
    • Fix: Update to modern APIs (check changelog for v7.0+).
  7. PSR-7 Conflicts:

    • Http class implements Psr7\UriInterface, but Uri does not.
    • Fix: Use Http for PSR-7 contexts:
      $psr7Uri = Http::new($uri->toString())->toPsr7Uri();
      
  8. Fragment Handling:

    • equals() considers fragments; isSameDocument() ignores them.
    • Fix: Use equals() for exact matches:
      $uri1->equals($uri2); // true if fragments match
      

Debugging Tips

  1. Validate URIs:

    if (!Uri::tryNew($string)) {
        throw new \InvalidArgumentException('Invalid URI');
    }
    
  2. Inspect Components:

    dump($uri->getComponents()); // Array of all components.
    
  3. Check RFC Compliance:

    $uri->toAsciiString(); // RFC 3986 encoding.
    $uri->toDisplayString(); // Human-readable IRI.
    
  4. Handle Exceptions:

    • UriException for parsing errors.
    • TemplateCanNotBeExpanded for invalid templates.
    • Fix: Use tryNew() or expandOrFail() for graceful handling:
      $uri = Uri::tryNew($string) ?? throw new \RuntimeException('Invalid URI');
      

Extension Points

  1. Custom URI Classes:
    • Extend Uri or Http for domain-specific logic:
      class ApiUri extends
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport