Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Retrieve HTTP response as a collection in Laravel 8.x

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']);
Learn the fundamentals of PHP 8 (and 8.1), 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-read 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.

👋 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?