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']);
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.