We use cookies on this site to enhance your user experience

By clicking the Accept button, you agree to us doing so. More info on our cookie policy

Using when with the Laravel Http Client

Published: Jan 28, 2024 by C.S. Rhymes

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;
}

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;
}

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;
}

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;
}

Photo by FOCA Stock on StockSnap

Laravel Http WebDev

Latest Posts

Marketing an ebook with the 4Ps
Marketing an ebook with the 4Ps

I have seen a lot of threads from indie authors asking for advice with marketing their ebook. If I’m honest, I have never really had a strategy for marketing my books, I just assumed that I could put it out there and people would find it. In the real world, that does not seem to be the case.

Building a landing page for your book
Building a landing page for your book

This post follows on from my last post about using your website to promote your ebooks. The first step of the article explains that you need to make a website, but didn’t go into too much detail. This post aims at explaining how you can build a landing page for your book with Bulma Clean Theme.

How to promote your ebooks with your website?
How to promote your ebooks with your website?

I’m a web developer by trade and a part-time author, so here are a few things that I have done to help promote my books and ebooks using my website and my tech know how from my day job.

How NOT to make a website

How NOT to make a Website

By C.S. Rhymes

From £5.49 or read for free on Kindle Unlimited!

Nigel's Intranet Adventure

Nigel's Intranet Adventure

By C.S. Rhymes

From £4.99 or read for free on Kindle Unlimited!