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

Amit Merchant

A blog on PHP, JavaScript, and more

Return HTTP response as a collection (Effectively) in Laravel

If you are using Laravel’s HTTP client to call a third-party API, you might want to use the response as a collection to manipulate the data.

The one way to use the json() method and then convert the response to a collection is to use the collect() method.

$response = Http::get('')->json('data');

$posts = collect($response);

However, there’s a more elegant way to do this. Essentially, the HTTP facade lets you collect the response as a collection natively by using the collect() method.

So, instead of using the json() method, you can use the collect() method directly.

$posts = Http::get('')->collect('data');

This is a more concise and readable way to do it.

I learned about this courtesy of this tweet.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), 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? Consider leaving a


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