Laravel's toUri() Method: Fluent URI Building from Strings

Ever needed to extract a URL from text and dynamically modify it with query parameters? Laravel's new toUri()
method transforms string manipulation into a fluent URI building experience.
Working with URLs embedded in text content has traditionally been a tedious process involving regular expressions, string parsing, and manual URL construction. Whether you're processing user-generated content, parsing configuration files, or handling dynamic redirects, extracting and modifying URIs often leads to brittle, hard-to-read code.
Laravel's toUri()
method elegantly bridges this gap by converting string content into powerful URI objects that support fluent method chaining. This approach combines Laravel's excellent string helpers with robust URI manipulation capabilities, creating a seamless developer experience for URL processing tasks.
Real-World Example
Consider a customer support system that needs to extract support URLs from templates and dynamically add user-specific parameters based on their account status:
$sentence = 'Go to {https://euhosting.com/support} for support.';
$uri = str($sentence)->between('{', '}')->toUri();
if (auth()->user()->isVip()) {
$uri = $uri->withQuery(['customer' => auth()->user()->publicId()])
->withQuery(['priority' => 'emergency']);
}
$finalUrl = $uri->value();
// Result: https://euhosting.com/support?customer=12345&priority=emergency
$templateUrl = 'Visit {https://api.example.com/v1/users} to manage your account.';
$apiUri = str($templateUrl)
->between('{', '}')
->toUri()
->withQuery(['token' => session('api_token')])
->withQuery(['format' => 'json'])
->withFragment('profile');
echo $apiUri->value();
// Result: https://api.example.com/v1/users?token=abc123&format=json#profile
This pattern is particularly powerful for email template processing, configuration management, API endpoint construction, and any scenario where you need to parse URLs from text and modify them programmatically. The fluent interface makes the transformation process self-documenting and eliminates the error-prone string concatenation typically required for URL manipulation.
The toUri()
method also integrates seamlessly with Laravel's existing string helpers, allowing you to chain multiple operations together. This creates readable, maintainable code that clearly expresses the intent of your URL processing logic.
Stay Updated with More Laravel Tips
Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:
- Follow us on Twitter @harrisrafto
- Join us on Bluesky @harrisrafto.eu
- Subscribe to our YouTube channel harrisrafto