Laravel Tutorials

Laravel Uri toStringable Method

Published
Laravel Uri toStringable Method image

The toStringable() method converts URI objects into Stringable instances, providing direct access to Laravel's string manipulation methods.

Previously, applying string transformations to URI objects required wrapping them with Str::of():

Str::of(Uri::of('http://localhost')->withScheme('https'));

The toStringable() method removes this extra step:

use Illuminate\Support\Uri;
 
Uri::of('http://localhost')->withScheme('https')->toStringable();

This maintains method chaining from URI construction through string operations:

$endpoint = Uri::of('http://api-service.com')
->withPath('/users')
->withQuery(['active' => 1, 'limit' => 25])
->toStringable()
->replace('/users', '/v2/users')
->lower()
->toString();

URL formatting for logging shows string method integration:

$logUrl = Uri::of('http://example.com/endpoint')
->withPath('/api/long/path/resource')
->toStringable()
->limit(40, '...')
->toString();
 
$masked = Uri::of('https://api.service.com/users/12345')
->toStringable()
->mask('*', -5, 5)
->toString();

The method provides access to all Stringable operations including case conversion, truncation, replacement, and masking without breaking the method chain or requiring helper function wrapping.

Harris Raftopoulos photo

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

Sponsored

acquaintsoft logo
Acquaint Softtech

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

Visit Acquaint Softtech

The latest

View all →
Taylor disabled GitHub Issues on most Laravel open-source packages. image

Taylor disabled GitHub Issues on most Laravel open-source packages.

Read article
Exclude Vendor and Default Commands in `php artisan dev` image

Exclude Vendor and Default Commands in `php artisan dev`

Read article
The Laracon Archive image

The Laracon Archive

Read article
Group Adjacent Collection Items in Laravel with chunkBy() image

Group Adjacent Collection Items in Laravel with chunkBy()

Read article
Laravel queue:work Now Prints Why the Worker Stopped image

Laravel queue:work Now Prints Why the Worker Stopped

Read article
Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites image

Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites

Read article