In Laravel
11.2.0, we got a fluent()
helper to conveniently
convert array data into a Fluent instance. Now, starting in Laravel
11.35, we have a convenient method for transforming an HTTP client
response into a fluent instance:
use Illuminate\Support\Facades\Http;
$response = Http::get('https://jsonplaceholder.typicode.com/posts')->fluent();
$response->get('0.title'); // sunt aut facere...
$response->collect()->pluck('title'); // ["sunt aut facere...", "qui est esse
", ...]
Another neat feature is converting JSON data into specific
types. Take this example where we can convert a string date into a
Carbon
instance:
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.chucknorris.io/jokes/random')->fluent();
$response->date('created_at');
$response->date('updated_at');
/*
Illuminate\Support\Carbon @1578231741 {#261 ▼ // routes/web.php:9
date: 2020-01-05 13:42:21.455187 UTC (+00:00)
}
*/
Fluent also supports other helpful types like
boolean
, enum
, array of
enum
, and more. One of my favorites is using familiar
methods like only
and except
to retrieve
specific data:
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.chucknorris.io/jokes/random')->fluent();
$response->except('categories'),
/*
array:6 [▼ // routes/web.php:9
"created_at" => "2020-01-05 13:42:19.897976"
"icon_url" => "https://api.chucknorris.io/img/avatar/chuck-norris.png"
"id" => "KqoQdIJdSE2ezokPmHSvdw"
"updated_at" => "2020-01-05 13:42:19.897976"
"url" => "https://api.chucknorris.io/jokes/KqoQdIJdSE2ezokPmHSvdw"
"value" => "One night Chuck Norris had Chili for dinner. The very next day the Big Bang happened."
]
*/
$response->only('id', 'url', 'value');
Learn More
I would recommend getting familiar with the Fluent class in the Laravel API docs. Fluent uses the InteractsWithData trait, which gives us a bunch of convenient methods for working with Fluent data.
The post Using Fluent to Work With HTTP Client Responses in Laravel appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/using-fluent-to-work-with-http-client-responses-in-laravel-11