Hello artisan hope you are doing well and enjoying reading blog from codecheef. In this tutorial we are going to learn about http response collection in laravel 8. That mean how we can make collection of our http responses using collect helper in Laravel.
Sometimes, you will see that when we work with HTTP responses, we might would like to fetch the entire response as a Laravel collection to make further manipulations. In this condition you can make http request like that:
$data = collect(
Http::get(
'https://jsonplaceholder.typicode.com/posts'
)->json()
);
Ok that's good but the latest release of Laravel 8.x, we can directly call the collect()
method on the HTTP client response like that:
$data = Http::get(
'https://jsonplaceholder.typicode.com/posts'
)->collect()
Now it will be really easy to fluently call other collection methods such as filter()
further like so:
$data = Http::get('https://jsonplaceholder.typicode.com/posts')
->collect()
->filter(fn($value, $key) => $value['is_published']);
Read also: Handle Exception Error in Laravel using Rescue Helper
Hope it can help you.
#laravel #http-request #laravel-8x #example #api #helper