Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Dynamic URLs with URI templates in Laravel

There comes a time when you want to make HTTP requests but the URL using which you want to make the request is dynamic. For example, you want to make a request to the GitHub API to get the details of a user but the username is dynamic. Or the version of the API is dynamic.

In such scenarios, you can use URI templates to make dynamic URLs in Laravel. In this article, we’ll see how to make dynamic URLs with URI templates in Laravel.

What is a URI template?

A URI Template is a way to specify a URI that includes parameters that must be substituted before the URI is resolved.

Essentially, a URI template is a URI that contains variables. These variables are enclosed in curly braces {}. For example, we can represent the URL https://api.github.com/v3/users/dhh using the following URI template.

{+endpoint}/{version}/{type}/{username}

This URI template can be used to make dynamic URLs.

Making dynamic URLs with URI templates

Laravel’s HTTP client provides a withUrlParameters() method that allows you to pass an array of options to specify the values of the variables in the URI template.

The method use guzzlehttp/uri-templates under-the-hood which follows this specification.

So, for instance, if we want to make a request to the GitHub API to get the details of a user, we can do it like so.

use Illuminate\Support\Facades\Http;

Http::withUrlParameters([
    'endpoint' => 'https://api.github.com',
    'version' => 'v3',
    'type' => 'users',
    'username' => 'dhh',
])->get('{+endpoint}/{version}/{type}/{username}');

// https://api.github.com/v3/users/dhh

As you can see, we can pass an array of options to the withUrlParameters() method. These options will be used to replace the variables in the URI template.

Now, if we want to make a request to the GitHub API to get the details of a user but the username is dynamic, all we need is to update the username key in the array with the dynamic username.

Or if we want to change the version of the API, we can simply change the value of the version key in the array.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?