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('https://test.com/posts')->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('https://test.com/posts')->collect('data');
This is a more concise and readable way to do it.
I learned about this courtesy of this tweet.
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.