Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Retrieve HTTP response as a collection in Laravel 8.x

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 (including 8.1, 8.2, 8.3, and 8.4), 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-digest 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?