Laravel Tutorials

Laravel's toUri() Method for Dynamic URL Construction

Published
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

Sponsored

laravelcloud logo
Laravel Cloud

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

Visit Laravel Cloud

The latest

View all →
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article