DEV Community

Cover image for Using when with the Laravel Http Client
C.S. Rhymes
C.S. Rhymes

Posted on • Originally published at csrhymes.com on

Using when with the Laravel Http Client

Here’s a little tip I discovered that I haven’t seen documented anywhere. You can use when() and unless() with the Laravel Http client.

Here is an example method that uses the Laravel Http client.

use Illuminate\Support\Facades\Http;

public function getUser(int $id): array
{
    $response = Http::baseUrl('https://example.com/api')
        ->get("user/{$id}")
        ->throw()
        ->json();

    return $response;
}
Enter fullscreen mode Exit fullscreen mode

Now imagine that we wanted to pass a token in that is sent as a header.

use Illuminate\Support\Facades\Http;

public function getUser(int $id, string $token): array
{
    $response = Http::baseUrl('https://example.com/api')
        ->withHeader('X-Token', $token)
        ->get("user/{$id}")
        ->throw()
        ->json();

    return $response;
}
Enter fullscreen mode Exit fullscreen mode

The Http client makes this very easy by using the ->withHeader() method.

But what happens if the token is optional for some calls? Some requests need it and others don’t?

Well, we could copy the whole method and duplicate all our code, or we could make use of ->when().

If you look into the PendingRequest class, you’ll see that it makes use of the Illuminate\Support\Traits\Conditionable trait. This trait gives it access to both when() and unless().

Here we set the token to be an optional parameter. When it is passed in, the when() resolves as true and then adds the closure.

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

public function getUser(int $id, ?string $token = null): array
{
    $response = Http::baseUrl('https://example.com/api')
        ->when($token, function (PendingRequest $request) {
            $request->withHeader('X-Token', $token);
        })
        ->get("user/{$id}")
        ->throw()
        ->json();

    return $response;
}
Enter fullscreen mode Exit fullscreen mode

You can also set a default method if you need to which runs when the when() resolves to false. An example could be setting a default token in the header if one is not provided.

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

public function getUser(int $id, ?string $token = null): array
{
    $response = Http::baseUrl('https://example.com/api')
        ->when($token, function (PendingRequest $request) {
            $request->withHeader('X-Token', $token);
        }, function (PendingRequest $request) {
            $request->withHeader('X-Token', 'default-value');
        })
        ->get("user/{$id}")
        ->throw()
        ->json();

    return $response;
}
Enter fullscreen mode Exit fullscreen mode

Photo by FOCA Stock on StockSnap

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay