Customize URL Handling with Laravel's Macroable URI Class

Published on by

Customize URL Handling with Laravel's Macroable URI Class image

Laravel enhances URL manipulation with the addition of the Macroable trait to the URI class, enabling developers to create custom URL handling methods that integrate seamlessly with the framework's elegant syntax.

The Illuminate\Support\Uri class provides a clean, object-oriented approach to working with URLs. It allows developers to parse, manipulate, and construct URLs without relying on PHP's native URL functions or string operations:

use Illuminate\Support\Uri;
 
$uri = new Uri('https://laravel.com/docs/10.x');
echo $uri->getHost(); // laravel.com
echo $uri->getPath(); // /docs/10.x

With the integration of the Macroable trait, this powerful API becomes even more flexible and customizable.

The Macroable trait represents a pattern used throughout Laravel that enables adding custom methods to existing classes at runtime. It provides a clean approach to extending functionality without modifying source code or creating complex inheritance structures.

Creating a URI macro is straightforward:

use Illuminate\Support\Uri;
 
Uri::macro('docs', fn () => $this->withPath('docs'));
 
$uri = new Uri('https://laravel.com/');
$docsUri = $uri->docs(); // https://laravel.com/docs

This macro adds a docs() method to all URI instances, which changes the path to "docs" in a clean, intuitive manner that reads like a native method.

In a practical application, you might need to generate different types of URLs for an e-commerce platform:

use Illuminate\Support\Uri;
 
// Register macros in a service provider
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Add category path to product URL
Uri::macro('inCategory', function ($category) {
return $this->withPath('shop/' . $category . '/' . trim($this->getPath(), '/'));
});
 
// Convert to mobile version
Uri::macro('mobile', function () {
$path = trim($this->getPath(), '/');
return $this->withHost('m.' . $this->getHost())
->withPath($path);
});
 
// Create tracking URL
Uri::macro('tracking', function ($campaign) {
return $this->withQueryParameter('utm_campaign', $campaign)
->withQueryParameter('utm_source', 'website');
});
}
}
 
// Usage in your application
$baseUri = new Uri('https://shopexample.com/products/winter-jacket');
 
// https://shopexample.com/shop/clothing/products/winter-jacket
$categoryUri = $baseUri->inCategory('clothing');
 
// https://m.shopexample.com/products/winter-jacket
$mobileUri = $baseUri->mobile();
 
// https://shopexample.com/products/winter-jacket?utm_campaign=winter-sale&utm_source=website
$trackingUri = $baseUri->tracking('winter-sale');

This approach creates a domain-specific language for URL manipulation that adapts perfectly to your application's specific requirements.

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

Laravel Cloud

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

Laravel Cloud
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
Lucky Media logo

Lucky Media

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

Lucky Media
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
Shift logo

Shift

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

Shift
PhpStorm logo

PhpStorm

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

PhpStorm
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
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 →
Building and Deploying a Laravel App With Claude Code on Zerops image

Building and Deploying a Laravel App With Claude Code on Zerops

Read article
The first hands-on AI Developer Certification image

The first hands-on AI Developer Certification

Read article
Heimdall: A Minimum Age Policy for Your Composer Dependencies image

Heimdall: A Minimum Age Policy for Your Composer Dependencies

Read article
Laravel Announces the Founders Summit, a One-Day Event for Founders image

Laravel Announces the Founders Summit, a One-Day Event for Founders

Read article
A Practical Guide to Laravel's First-Party Image Processing image

A Practical Guide to Laravel's First-Party Image Processing

Read article
RouteKey Model Attribute in Laravel 13.21 image

RouteKey Model Attribute in Laravel 13.21

Read article