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

zenstruck/uri

Immutable, fluent URI/URL value objects for PHP with easy parsing, building, and modification of URIs. Create, normalize, and manipulate components (scheme, host, path, query, fragment) safely, with helpers for encoding and query params.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require zenstruck/uri
    

    No additional configuration is required—it’s a drop-in package.

  2. First Use Case Parse and manipulate a URL as an object:

    use Zenstruck\Uri\Uri;
    
    $uri = Uri::fromString('https://example.com/path?query=value#fragment');
    echo $uri; // Outputs: https://example.com/path?query=value#fragment
    
  3. Key Initial Methods

    • Uri::fromString(string $url) – Parse a string into a Uri object.
    • Uri::fromParts(array $parts) – Build from an associative array (e.g., parse_url() output).
    • Uri::fromRequest(Request $request) – Parse from a Laravel Request object (includes query params).
  4. Where to Look First

    • Class Documentation (methods like getScheme(), getHost(), getPath(), etc.).
    • Tests for edge cases (e.g., relative URLs, malformed inputs).

Implementation Patterns

Core Workflows

  1. URL Construction

    $uri = Uri::fromString('https://example.com')
        ->withPath('/new-path')
        ->withQuery(['key' => 'value'])
        ->withFragment('section');
    
    • Chain methods for immutable updates (returns new Uri instances).
  2. Query Parameter Handling

    $uri = Uri::fromString('https://example.com?foo=bar&baz=qux');
    $uri->getQuery('foo'); // 'bar'
    $uri->withQuery(['foo' => 'updated']); // New Uri with updated query
    $uri->withoutQuery('baz'); // Removes 'baz'
    
  3. Relative URL Resolution

    $base = Uri::fromString('https://example.com/base/');
    $relative = Uri::fromString('subpath');
    $absolute = $base->resolve($relative); // 'https://example.com/base/subpath'
    
  4. Laravel Integration

    • Request Parsing:
      $uri = Uri::fromRequest(request());
      
    • Redirects:
      return redirect()->to(Uri::fromString('/new-path')->withQuery(['ref' => 'home']));
      
    • Route Generation:
      $uri = Uri::fromRoute('profile.show', ['user' => 1]);
      
  5. Validation

    if ($uri->isValid()) {
        // Safe to use
    }
    

Advanced Patterns

  • URL Normalization:
    $uri = Uri::fromString('  Http://EXAMPLE.COM/path  ');
    $uri->normalize(); // 'http://example.com/path'
    
  • Scheme/Host Manipulation:
    $uri->withScheme('https')->withHost('api.example.com');
    
  • Serialization:
    $uri->toString(); // Back to string
    $uri->toArray();  // Associative array (like parse_url)
    

Gotchas and Tips

Pitfalls

  1. Immutable Updates

    • Methods like withPath() return new Uri instances. Avoid overwriting the original:
      // Anti-pattern: Loses previous state
      $uri = Uri::fromString('https://example.com');
      $uri = $uri->withPath('/new'); // Correct
      $uri->withQuery([]); // Overwrites if reused!
      
  2. Query Parameter Conflicts

    • withQuery() replaces all query params. Use withAddedQuery() or withoutQuery() for granular control:
      $uri->withAddedQuery(['page' => 2]); // Preserves existing params
      
  3. Relative URL Edge Cases

    • resolve() may not handle all edge cases (e.g., ../ in paths). Test with:
      $base = Uri::fromString('https://example.com/base/');
      $relative = Uri::fromString('../../outside');
      $absolute = $base->resolve($relative); // 'https://example.com/outside'
      
  4. Case Sensitivity

    • Schemes/hosts are case-insensitive but preserved as-is. Normalize with normalize() if needed.
  5. Empty Components

    • Methods like getPath() return null for missing components (not empty string). Check for null explicitly.

Debugging Tips

  • Inspect Parts:
    $uri->toArray(); // Debug all components
    
  • Validate Early:
    if (!$uri->isValid()) {
        throw new \InvalidArgumentException('Invalid URI');
    }
    
  • Use toString() for Logging:
    \Log::debug('Generated URI', ['uri' => $uri->toString()]);
    

Extension Points

  1. Custom Parsing Logic Override Uri::fromString() behavior by extending the class:

    class CustomUri extends Uri {
        public static function fromString(string $url): self {
            // Custom logic (e.g., default scheme)
            return parent::fromString($url);
        }
    }
    
  2. Add Custom Methods

    $uri->withTld('com'); // Hypothetical; extend to add domain-specific logic
    
  3. Integrate with Laravel Services Bind the package to the container in AppServiceProvider:

    $this->app->bind('uri', function () {
        return Uri::fromRequest(request());
    });
    
  4. Handle Non-Standard URLs For URLs with non-standard schemes (e.g., mailto:), ensure the package’s isValid() logic aligns with your needs (may require extending).

Config Quirks

  • No Configuration File: The package is zero-config. All behavior is runtime-driven.
  • Default Scheme: If parsing a relative URL (e.g., /path), the scheme defaults to null. Explicitly set it if needed:
    $uri = Uri::fromString('/path')->withScheme('https');
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor