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 provides simple, intuitive PHP 8.1+ classes to parse, validate, normalize, and manipulate URIs and related components. Supports PSR-7 interoperability, IDN hosts (intl/polyfill), IPv4 conversion, and HTML URI handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/uri
    

    Requires PHP 8.1+ and extensions: intl (for IDN), dom (for HTML), and either GMP, BCMath, or 64-bit PHP (for IPv4).

  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"
    echo $uri->getPath(); // "/path"
    
  3. Key Classes:

    • Uri: Core class for URI manipulation (RFC 3986).
    • Http: PSR-7 compliant HTTP URI subclass.
    • UriTemplate: For URI template expansion (RFC 6570).
    • Urn: For URN (Uniform Resource Name) handling (RFC 8141).
  4. Documentation: Start with the official docs for API references and examples.


Implementation Patterns

Common Workflows

1. URI Construction

  • From a string:
    $uri = Uri::new('https://example.com');
    
  • From components:
    $uri = Uri::fromComponents([
        'scheme' => 'https',
        'host'   => 'example.com',
        'path'   => '/api/v1',
    ]);
    
  • From server variables (e.g., $_SERVER):
    $uri = Uri::fromServer($_SERVER);
    

2. URI Manipulation

  • Modify components immutably (returns a new instance):
    $newUri = $uri->withPath('/new-path');
    $newUri = $uri->withQuery(['key' => 'value']);
    
  • Resolve relative URIs:
    $baseUri = Uri::new('https://example.com/base');
    $relativeUri = Uri::new('/relative');
    $resolved = $baseUri->resolve($relativeUri);
    // Resolves to: https://example.com/relative
    
  • Normalize URIs:
    $normalized = $uri->normalize(); // Decodes %-encoded chars, normalizes paths.
    

3. URI Templates

  • Expand templates:
    $template = UriTemplate::new('https://api.example.com/{user}');
    $uri = $template->expand(['user' => 'john-doe']);
    // Expands to: https://api.example.com/john-doe
    
  • Conditional building:
    $uri = Uri::new('https://example.com')
        ->when($isAdmin, fn($u) => $u->withPath('/admin'))
        ->when($isGuest, fn($u) => $u->withPath('/guest'));
    

4. HTTP-Specific Operations

  • PSR-7 compliance:
    $httpUri = Http::new('https://example.com');
    $psr7Uri = $httpUri->toPsr7Uri(); // Returns a PSR-7 UriInterface.
    
  • Origin checks:
    $isSameOrigin = $uri->isSameOrigin($otherUri);
    $isCrossOrigin = $uri->isCrossOrigin($otherUri);
    

5. Validation and Checks

  • Scheme validation:
    if ($uri->getScheme() === 'https') { ... }
    
  • Host type checks:
    $uri->isIpv4Host(); // true/false
    $uri->isDomainHost(); // true/false
    
  • Same-document checks:
    $uri->isSameDocument($otherUri); // Ignores fragment.
    $uri->equals($otherUri); // Includes fragment.
    

6. Integration with Laravel

  • Request/Response URIs:
    use Illuminate\Http\Request;
    $uri = Uri::fromServer(request()->server());
    
  • Route generation:
    $routeUri = Uri::new(route('profile', ['user' => 'john']));
    
  • Redirects:
    return redirect()->to($uri->toString());
    

7. URI Templates in Laravel

  • Dynamic API endpoints:
    $template = UriTemplate::new('https://api.example.com/v1/{resource}/{id}');
    $uri = $template->expand(['resource' => 'users', 'id' => 123]);
    

8. File URIs

  • Local file handling:
    $fileUri = Uri::fromFileContents(__FILE__);
    $fileUri->isLocalFile(); // true
    

Integration Tips

Laravel Service Provider

Register a global URI helper:

// app/Providers/AppServiceProvider.php
use League\Uri\Uri;
use Illuminate\Support\Facades\URL;

public function boot()
{
    URL::macro('parse', function ($uri) {
        return Uri::parse($uri);
    });
}

Usage:

$uri = URL::parse('https://example.com');

Form Request Validation

Validate URIs in Laravel forms:

use League\Uri\Uri;
use Illuminate\Validation\Rule;

$request->validate([
    'redirect_url' => [
        'required',
        Rule::function('valid_uri', function ($attribute, $value) {
            return Uri::tryNew($value) !== null;
        }),
    ],
]);

API Response Headers

Set Location headers with URIs:

return response()->header('Location', $uri->toString())->setStatusCode(302);

URI-Based Caching

Generate cache keys from URIs:

$cacheKey = 'uri:' . md5($uri->toAsciiString());

Testing

Mock URIs in tests:

$mockUri = Mockery::mock(Uri::class);
$mockUri->shouldReceive('getHost')->andReturn('test.com');

Gotchas and Tips

Pitfalls

1. Immutable Operations

  • Issue: Forgetting that URI methods like withPath() return a new instance.
    $uri->withPath('/new'); // Does NOT modify $uri!
    
  • Fix: Reassign the result:
    $uri = $uri->withPath('/new');
    

2. IDN (Internationalized Domain Names)

  • Issue: Missing intl extension throws exceptions for non-ASCII hosts (e.g., 例子.测试).
  • Fix: Install intl or use a polyfill like symfony/polyfill-intl-idn:
    composer require symfony/polyfill-intl-idn
    

3. IPv4/IPv6 Handling

  • Issue: IPv6 addresses must be properly formatted (e.g., [2001:db8::1]).
  • Fix: Use Uri::new('http://[2001:db8::1]') or validate with:
    $uri->isIpv6Host();
    

4. Path Normalization

  • Issue: Leading/trailing slashes in paths may cause unexpected behavior.
  • Fix: Use normalize() or Uri::fromComponents() for consistency:
    $uri = Uri::fromComponents(['path' => '/path/to/resource']);
    

5. Query String Order

  • Issue: Query parameters may not retain insertion order.
  • Fix: Use withQuery() with an ordered array:
    $uri->withQuery(['page' => 1, 'sort' => 'asc']);
    

6. Fragment Handling

  • Issue: isSameDocument() ignores fragments, while equals() includes them.
  • Fix: Choose the method based on your needs:
    $uri->isSameDocument($otherUri); // Ignores #fragment
    $uri->equals($otherUri); // Considers #fragment
    

7. Deprecated Methods

  • Issue: Using deprecated methods (e.g., Uri::fromBaseUri).
  • Fix: Update to modern methods:
    // Old (deprecated)
    Uri::fromBaseUri($base, $relative);
    
    // New
    $base->resolve($relative);
    

8. PSR-7 Compatibility

  • Issue: Http class is PSR-7 compliant but may behave differently than Uri.
  • Fix: Use Http for HTTP-specific logic and Uri for general cases.

9. URI Template Variables

  • **Issue
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui