Laravel Tutorials

Working with Laravel's Uri Class for Enhanced URL Manipulation

Published
Working with Laravel's Uri Class for Enhanced URL Manipulation image

Laravel introduces a powerful Uri class that transforms how you handle and manipulate URLs. This elegant abstraction provides a fluent interface for URI operations, making complex URL transformations more intuitive.

The basic implementation showcases its clean syntax:

$uri = Uri::of('https://laravel.com')
->withQuery(['name' => 'Taylor'])
->withPath('/docs/installation')
->withFragment('hello-world');
// https://laravel.com/docs/installation?name=Taylor#hello-world

Here's a practical example demonstrating Uri class usage in a content distribution service:

class ContentDistribution
{
public function createCampaignUrl(string $baseUrl, Campaign $campaign)
{
return Uri::of($baseUrl)
->withPath('/content/' . $campaign->slug)
->withQuery([
'source' => $campaign->source,
'medium' => $campaign->medium,
'campaign' => $campaign->name,
'token' => $this->generateToken($campaign->id)
]);
}
 
public function buildEmbeddableLinks(Media $media)
{
$baseUrl = config('app.media_url');
$mediaUrl = Uri::of($baseUrl)->withPath('/embed/' . $media->uuid);
 
return [
'standard' => (string) $mediaUrl,
'autoplay' => (string) $mediaUrl->withQuery(['autoplay' => 1]),
'timestamped' => (string) $mediaUrl->withQuery([
'start' => $media->highlight_timestamp,
'theme' => 'dark'
]),
'iframe_src' => (string) $mediaUrl->withQuery(['iframe' => 1])
];
}
}

Laravel's Uri class significantly improves code readability when working with complex URLs, while providing a safer approach to URL manipulation that avoids common string concatenation errors.

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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article