Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Making Conditional Requests with the Laravel HTTP Client

When PHP code sends a request to an external API, it may need to choose headers, payload fields, or a URL based on values available at runtime, such as whether a feature flag is on or a token is available. In Laravel 13, PHP can make those choices before sending the request. Use the HTTP client’s when method to configure a request based on a condition, and ordinary PHP checks to build payloads or choose URLs.

Here, “conditional” means that PHP adds or changes parts of an outgoing request based on a condition. Laravel’s PendingRequest is an object you configure before sending a request. Its when and unless methods run callbacks based on whether a condition evaluates to true or false. The examples below show how to add a header, include an optional payload field, and choose a URL at runtime.

Add headers only when a condition passes

Use when to change a request only when its condition is true. This example adds an authorization token when one is available and adds a version header when the account uses the newer API.

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

$useV2 = $account->usesV2Api();
$token = config('services.catalog.token');

$request = Http::acceptJson()
    ->when(
        $token !== null && $token !== '',
        fn (PendingRequest $request) => $request->withToken($token)
    )
    ->when(
        $useV2,
        fn (PendingRequest $request) => $request->withHeader('X-Api-Version', '2')
    );

The explicit token check matters because when treats a condition according to PHP’s truthiness rules: some values count as true and others as false. The check $token !== null && $token !== '' states exactly which values count as a usable token. Laravel documents withHeader and withHeaders for setting headers. withHeaders merges the supplied values with headers already set on the request. The Laravel HTTP client documentation also describes replaceHeaders, which replaces the configured headers.

Use unless when the callback should run if the condition is false. For example, ->unless($useV2, $callback) runs the callback when $useV2 is false. The Laravel API reference for PendingRequest documents both methods.

Include payload fields deliberately

Build the payload in PHP and add optional fields only when their conditions are true. Laravel’s post method takes the destination URL and data. The HTTP client sends that data as JSON by default.

$payload = [
    'sku' => $sku,
];

if ($requestMetadata !== []) {
    $payload['metadata'] = $requestMetadata;
}

This check leaves out metadata when the array is empty and keeps other values that may be meaningful even when PHP treats them as false. Do not filter the whole payload by truthiness unless you intend to remove every value PHP treats as false, including false or 0.

Select the endpoint before sending

Use the same runtime condition to choose the URL, then send the request with the payload:

$url = $useV2
    ? 'https://api.example.test/v2/items'
    : 'https://api.example.test/v1/items';

$response = $request->post($url, $payload);

A ternary keeps the code short when only the URL changes. Use an if/else branch when each option also needs a different method, payload, or header. Laravel’s request methods take the URL when PHP sends the request. PHP uses the condition to choose that URL.

Test both outcomes

Use Laravel’s HTTP testing helpers to check what the code sends without contacting the external service. Http::fake() prevents a live request. Http::assertSent() lets a test check which URL the request uses, which headers it sends, and what data it carries. Test the enabled and disabled conditions separately. Check that the enabled case uses the expected URL and header, and that the other case uses its alternate URL and leaves out data or headers that only apply when the condition is enabled. Use Http::assertNotSent() to confirm that a matching request was not sent.

The HTTP client testing documentation describes these request assertions. Make the test conditions match the conditions in your code. Then the test fails if either branch sends the wrong URL or includes a field that should be left out.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *