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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
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
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
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
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
PhpStorm logo

PhpStorm

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

PhpStorm
Tinkerwell logo

Tinkerwell

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

Tinkerwell
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 →
Passwordless Sign-In with Fortify Two-Factor Support in Laravel image

Passwordless Sign-In with Fortify Two-Factor Support in Laravel

Read article
Intercept: Middleware Guardrails for Laravel AI Agents image

Intercept: Middleware Guardrails for Laravel AI Agents

Read article
AI Review for Laravel Upgrades image

AI Review for Laravel Upgrades

Read article
HTTP Query Method Support in Laravel 13.19 image

HTTP Query Method Support in Laravel 13.19

Read article
Ship AI with Laravel: I Tricked My Own AI Into Leaking Everything image

Ship AI with Laravel: I Tricked My Own AI Into Leaking Everything

Read article
Laravel MPP: Charge AI Agents for API Access with 402 Payment Required image

Laravel MPP: Charge AI Agents for API Access with 402 Payment Required

Read article