Retrieve HTTP response as a collection in Laravel 8.x

Amit Merchant · February 27, 2021 ·

Sometimes, when working with HTTP responses, you might want to retrieve the entire response as a Laravel collection to make further manipulations.

For instance, if you want to convert the HTTP response to a Laravel collection, you can do it like so.

$posts = collect(
    Http::get(
        'https://jsonplaceholder.typicode.com/posts'
    )->json()
);

This is good. But with the latest release of Laravel 8.x, you can directly call the collect() method on the HTTP client response. So, the previous example can be rewritten using the collect() method like so.

$posts = Http::get(
    'https://jsonplaceholder.typicode.com/posts'
)->collect()

As you can tell, calling the collect() method on the response itself makes the syntax more terse and easy to process.

On top of this, it would be really easy to fluently call other collection methods such as filter() further like so.

$posts = Http::get('https://jsonplaceholder.typicode.com/posts')
    ->collect()
    ->filter(fn($value, $key) => $value['is_published']);

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?