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

Url Laravel Package

spatie/url

Immutable URL parser/builder for PHP. Parse scheme, host, path and query, then fluently transform parts (withHost, withPath, withScheme) and manage query parameters. Supports allowed/sanitized schemes for safer URL handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer:

composer require spatie/url

Start by parsing an existing URL or building a new one:

use Spatie\Url\Url;

// Parse from string
$url = Url::fromString('https://example.com/path?foo=bar#section');

// Build from components
$url = Url::fromParts([
    'scheme' => 'https',
    'host'   => 'example.com',
    'path'   => '/path',
    'query'  => ['foo' => 'bar'],
    'fragment' => 'section',
]);

First common use case: append query parameters to the current request URL.

$current = Url::fromString($_SERVER['REQUEST_URI'] ?? '');
$newUrl  = $current->withQuery('next', '/dashboard');

Implementation Patterns

  • Fluent mutation & chaining: Prefer with*() methods for immutable transformations.
    $url = Url::fromString('https://example.com')
        ->withPath('/api/v1/users')
        ->withQuery('limit', 50)
        ->withoutQuery('offset');
    
  • Bulk query handling: Use arrays or closures for complex query manipulation.
    $url = $url->withQuery(['foo' => 'bar', 'baz' => 'qux']); // replace all
    // Or additive:
    $url = $url->addQuery('foo', 'bar')->addQuery('foo', 'baz'); // foo=bar&foo=baz
    
  • URL normalization: Ensure consistent encoding & trailing slash behavior.
    $normalized = $url->withoutTrailingSlash()->normalizePath()->normalizeQuery();
    
  • Integration with Laravel: Use in services or macros to build canonical URLs or redirect chains.
    // In a service provider
    Url::macro('canonical', fn () => Url::fromString(url()->current())->withoutQuery('utm_*')->withoutFragment());
    

Gotchas and Tips

  • Immutable by design: Methods like withQuery() return a new instance—forgetting to assign the result is a common source of bugs.
  • Query parameter ordering: The package preserves insertion order only if you use addQuery() sequentially; withQuery(['a' => 1, 'b' => 2]) is deterministic, but array order can be surprising.
  • Special characters in paths/fragments: Url::fromString() auto-decodes percent-encoded segments, but __toString() re-encodes safely—avoid manual concatenation to prevent double-encoding.
  • Empty vs missing query: withQuery('', 'value') adds a key with empty value (?=value), whereas omitting the key entirely requires withQuery([], ['key' => 'value']).
  • For redirects: Always use __toString() or ->__toString() explicitly in headers—PHP may not auto-cast.
  • Extensibility: Override Url::fromString() in your own subclass to inject custom parsing (e.g., for legacy systems with nonstandard URLs).
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