Polyscope - The agent-first dev environment for Laravel

Laravel's toUri() Method for Dynamic URL Construction

Last updated on by

Laravel's toUri() Method for Dynamic URL Construction image

Laravel's toUri() method transforms string-based URL extraction into fluent URI manipulation, enabling dynamic parameter addition and modification through method chaining.

Traditional URL processing requires complex string manipulation and parsing logic:

$text = 'Visit {https://api.service.com/endpoint} for data access.';
preg_match('/\{(.*?)\}/', $text, $matches);
$baseUrl = $matches[1];
$finalUrl = $baseUrl . '?' . http_build_query($params);

The new approach streamlines this into readable, chainable operations that integrate with Laravel's string helpers.

$uri = str($text)->between('{', '}')->toUri();
$finalUrl = $uri->withQuery(['key' => 'value'])->value();

Here's a comprehensive notification system demonstrating various URI manipulation scenarios:

class NotificationService
{
public function processEmailTemplate(string $template, User $user): string
{
$actionUrl = str($template)
->between('[ACTION_URL]', '[/ACTION_URL]')
->toUri();
 
if ($user->hasRole('premium')) {
$actionUrl = $actionUrl
->withQuery(['tier' => 'premium'])
->withQuery(['features' => 'advanced'])
->withFragment('dashboard');
} else {
$actionUrl = $actionUrl
->withQuery(['tier' => 'basic'])
->withQuery(['upgrade' => 'available']);
}
 
$trackingUrl = $actionUrl
->withQuery(['utm_source' => 'email'])
->withQuery(['utm_campaign' => 'user_engagement'])
->withQuery(['user_id' => $user->id]);
 
return str($template)->replace(
'[ACTION_URL]' . str($template)->between('[ACTION_URL]', '[/ACTION_URL]') . '[/ACTION_URL]',
$trackingUrl->value()
);
}
 
public function generateApiEndpoints(array $baseUrls, array $parameters): array
{
$endpoints = [];
 
foreach ($baseUrls as $service => $url) {
$uri = str($url)->toUri();
 
$uri = $uri->withQuery(['api_version' => $parameters['version'] ?? 'v1'])
->withQuery(['format' => $parameters['format'] ?? 'json']);
 
if (isset($parameters['auth_token'])) {
$uri = $uri->withQuery(['token' => $parameters['auth_token']]);
}
 
if (isset($parameters['timeout'])) {
$uri = $uri->withQuery(['timeout' => $parameters['timeout']]);
}
 
$endpoints[$service] = $uri->value();
}
 
return $endpoints;
}
 
public function buildDownloadLinks(Collection $files, string $baseTemplate): Collection
{
return $files->map(function ($file) use ($baseTemplate) {
$downloadUri = str($baseTemplate)
->replace('{FILE_ID}', $file->id)
->toUri();
 
$downloadUri = $downloadUri
->withQuery(['expires' => now()->addHours(24)->timestamp])
->withQuery(['signature' => $this->generateSignature($file)])
->withQuery(['download' => 'true']);
 
if ($file->requires_authentication) {
$downloadUri = $downloadUri->withQuery(['auth' => 'required']);
}
 
return [
'file_id' => $file->id,
'name' => $file->name,
'download_url' => $downloadUri->value(),
'expires_at' => now()->addHours(24)->toISOString()
];
});
}
 
public function createWebhookUrls(string $configTemplate, array $webhookData): array
{
$webhooks = [];
 
foreach ($webhookData as $event => $endpoint) {
$webhookUri = str($configTemplate)
->replace('{ENDPOINT}', $endpoint)
->toUri();
 
$webhookUri = $webhookUri
->withQuery(['event' => $event])
->withQuery(['secret' => $this->generateWebhookSecret()])
->withQuery(['version' => '2024-07']);
 
if ($event === 'payment_completed') {
$webhookUri = $webhookUri
->withQuery(['priority' => 'high'])
->withQuery(['retry_count' => '3']);
}
 
$webhooks[$event] = [
'url' => $webhookUri->value(),
'secret' => $this->generateWebhookSecret(),
'events' => [$event]
];
}
 
return $webhooks;
}
 
private function generateSignature($file): string
{
return hash_hmac('sha256', $file->id . $file->name, config('app.key'));
}
 
private function generateWebhookSecret(): string
{
return 'whsec_' . bin2hex(random_bytes(24));
}
}
 
class RedirectController extends Controller
{
public function buildRedirectUrl(Request $request): string
{
$baseRedirect = 'https://app.example.com/dashboard';
 
$redirectUri = str($baseRedirect)->toUri();
 
if ($request->has('campaign')) {
$redirectUri = $redirectUri->withQuery(['utm_campaign' => $request->input('campaign')]);
}
 
if ($request->has('source')) {
$redirectUri = $redirectUri->withQuery(['utm_source' => $request->input('source')]);
}
 
if (auth()->check()) {
$redirectUri = $redirectUri
->withQuery(['user' => auth()->id()])
->withFragment('welcome');
} else {
$redirectUri = $redirectUri->withFragment('login');
}
 
return $redirectUri->value();
}
}

The toUri() method simplifies URL manipulation while maintaining Laravel's fluent interface conventions, making complex URI construction both readable and maintainable.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel Sluggable image

Laravel Sluggable

Read article
Ship AI with Laravel: RAG with Embeddings and pgvector in Laravel 13 image

Ship AI with Laravel: RAG with Embeddings and pgvector in Laravel 13

Read article
Laravel Mobile Pass: Generate Apple Wallet and Google Wallet Passes image

Laravel Mobile Pass: Generate Apple Wallet and Google Wallet Passes

Read article
PHPverse 2026 Returns June 9th image

PHPverse 2026 Returns June 9th

Read article
LLPhant: A PHP Generative AI Framework Inspired by LangChain image

LLPhant: A PHP Generative AI Framework Inspired by LangChain

Read article
Debounceable Queued Jobs in Laravel 13.6.0 image

Debounceable Queued Jobs in Laravel 13.6.0

Read article