Build URLs with Laravel's Uri Class
Building URLs dynamically often involves concatenating strings or manually handling query parameters.
For example:
$url = 'https://example.com/products?page=2&sort=latest';
This becomes harder to maintain when URLs contain dynamic parameters.
Laravel provides the Uri class to make URL creation and modification cleaner.
Create a URI
use Illuminate\Support\Uri;
$uri = Uri::of('https://example.com/products');
You now have a URI object instead of a plain string.
Modify URL Components
You can fluently change different parts of a URL:
$uri = Uri::of('https://example.com')->withScheme('https')
->withHost('shop.example.com')
->withPath('/products')
->withQuery(['page' => 2])
->withFragment('product-list');
Each method returns a URI instance, allowing you to chain multiple modifications.
Add Query Parameters
Imagine building a product search URL with dynamic filters:
$uri = Uri::of('https://example.com/products')->withQuery([
'category' => 'electronics',
'sort' => 'price',
'page' => 2,
]);
This keeps query parameter handling separate from URL string construction.
Generate URLs from Named Routes
You can also create URI objects directly from your Laravel routes:
$uri = Uri::route('products.show', [
'product' => 10,
]);
This is particularly useful when you want to generate a route URL and then modify it further.
Real-World Example
Imagine generating a filtered product link for an external integration:
$uri = Uri::route('products.index')
->withQuery([
'category' => 'laptops',
'availability' => 'in_stock',
'sort' => 'latest',
]);
$url = (string) $uri;
Now you can pass the generated URL to an API response, email, or another service.