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 Components Laravel Package

league/uri-components

Immutable value objects for concrete URI components (host, path, query, etc.) in the League URI ecosystem. Requires PHP 8.1+. Supports IDN hosts with intl (or polyfill) and IPv4 conversion via GMP/BCMath or 64-bit PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/uri-components
    

    Requires PHP 8.1+ and extensions like intl (for IDN) or GMP/BCMath (for IPv4).

  2. First Use Case: Parse and manipulate a URL:

    use League\Uri\Components\Uri;
    
    $uri = Uri::createFromString('https://example.com/path?query=value#fragment');
    $scheme = $uri->scheme(); // Returns "https"
    $host = $uri->host();     // Returns "example.com"
    
  3. Key Classes to Explore:

    • Uri (top-level container)
    • Query (for query strings)
    • Modifier (for fluent URI modifications)
    • Domain, Path, Fragment (individual components)

Implementation Patterns

Common Workflows

1. URI Construction & Parsing

// From string
$uri = Uri::createFromString('https://api.example.com/v1/users?id=123');

// From components
$uri = Uri::create()
    ->withScheme('https')
    ->withHost('api.example.com')
    ->withPath('/v1/users')
    ->withQuery('id=123');

2. Query String Manipulation

$query = $uri->query();
$query->with('page', 2); // Append/update
$query->without('sort'); // Remove
$query->appendList('tags', ['php', 'laravel']); // Handle arrays

3. Fluent Modifications with Modifier

$modifiedUri = $uri->modifier()
    ->withPath('/v2/users')
    ->appendQuery('limit=10')
    ->redactUserInfo()
    ->toUri();

4. Domain/Path Operations

$domain = $uri->host()->domain();
$domain->isSubdomainOf('example.com'); // true

$path = $uri->path();
$path->prepend('api/'); // "/api/v1/users"

5. Validation & Normalization

$uri->scheme()->isHttp(); // true
$uri->host()->normalized(); // IDN/ASCII conversion

Integration Tips

Laravel-Specific Patterns

  1. Request URI Handling:

    use League\Uri\Components\Uri;
    use Illuminate\Http\Request;
    
    $requestUri = Uri::createFromString(request()->getUri());
    $query = $requestUri->query()->all(); // Convert to array
    
  2. Route Generation:

    $uri = Uri::create()
        ->withScheme('https')
        ->withHost(config('app.url'))
        ->withPath(route('users.index'));
    
  3. Form Data to Query:

    $query = Query::fromFormData(request()->all());
    $uri->withQuery($query);
    

PSR-7 Compatibility

use League\Uri\Components\Modifier;
use Psr\Http\Message\UriInterface;

$modifier = Modifier::wrap($psr7Uri);
$modifiedPsr7Uri = $modifier->withPath('/new-path')->unwrap();

Gotchas and Tips

Pitfalls

  1. Immutable Objects: All components (e.g., Query, Path) are immutable. Use modifier methods (e.g., with(), append()) to create new instances.

    // ❌ Won't work (no setter)
    $query->set('key', 'value');
    
    // ✅ Correct
    $newQuery = $query->with('key', 'value');
    
  2. Query String Encoding: Use Query::encoded() or Modifier::encodeQuery() for safe URL encoding.

    $query->with('search', 'Laravel & PHP')->encoded();
    // Output: "search=Laravel+%26+PHP"
    
  3. IDN Hosts: Requires intl extension or symfony/polyfill-intn-idn. Fallback to ASCII if unavailable.

    try {
        $uri->withHost('例子.测试'); // IDN
    } catch (\InvalidArgumentException $e) {
        // Handle missing intl
    }
    
  4. Path Segments: Leading/trailing slashes matter. Use Path::normalized() to standardize.

    $path = Path::create('/users/')->normalized(); // "/users"
    
  5. Backward Compatibility: Methods like Modifier::uri() are deprecated. Use Modifier::unwrap() or Modifier::toUri().


Debugging Tips

  1. Inspect Components:

    $uri->toString(); // Full URI
    $uri->query()->all(); // Query as array
    $uri->path()->segments(); // ["users", "123"]
    
  2. Query Validation:

    $query->has('page'); // Check existence
    $query->get('page', 1); // Default value
    
  3. Modifier Debugging: Use Modifier::wrap() to inspect intermediate states:

    $modifier = Modifier::wrap($uri);
    $modifier->withPath('/debug')->toString();
    

Extension Points

  1. Custom Query Parsing: Override Query::fromString() or use Query::fromPairs() with custom logic.

  2. Domain Validation: Extend Domain to add custom rules (e.g., regex validation).

  3. Modifier Chaining: Create reusable modifier chains:

    $modifier = Modifier::wrap($uri)
        ->withScheme('https')
        ->withHost('api.example.com')
        ->appendPath('/v1');
    
  4. PSR-7 Bridge: Use Modifier::wrap() to integrate with frameworks like Lumen or Symfony.


Laravel-Specific Quirks

  1. Route Parameters: Use Uri::create()->withPath(route('name', $params)) to avoid manual string concatenation.

  2. Asset URLs: Combine with Laravel’s asset() helper:

    $uri = Uri::create()->withPath(asset('images/logo.png'));
    
  3. Redirects:

    return redirect()->to(
        Uri::create()
            ->withScheme('https')
            ->withHost(request()->getHost())
            ->withPath('/new-location')
    );
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope