Laravel покращує взаємодію з API завдяки новому методу fluent() в обробці відповідей HTTP Client. Ця функція забезпечує безпечний доступ до даних відповіді, що спрощує роботу з зовнішніми API.
Метод перетворює відповіді у "вільні" об'єкти з доступом до специфічних типів:
$response = Http::get('https://api.example.com/products/1')->fluent();
$price = $response->float('price'); // 420.69
$colors = $response->collect('colors'); // Collection(['red', 'blue'])
$onSale = $response->boolean('on_sale'); // true
$stock = $response->integer('current_stock'); // 69
Ось приклад реалізації у сервісі прогнозу погоди:
class WeatherService
{
protected string $apiKey;
protected string $baseUrl = 'https://weather-api.example.com';
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
public function getLocationForecast(string $city)
{
$response = Http::withToken($this->apiKey)
->get("{$this->baseUrl}/forecast", [
'city' => $city,
'units' => 'metric'
])
->throw()
->fluent();
return [
'location' => [
'city' => $response->string('city'),
'country' => $response->string('country'),
'coordinates' => $response->collect('coordinates')->toArray()
],
'current' => [
'temperature' => $response->float('current.temperature'),
'feels_like' => $response->float('current.feels_like'),
'humidity' => $response->integer('current.humidity'),
'wind_speed' => $response->float('current.wind.speed')
],
'forecast' => $response->collect('forecast')->map(function ($day) {
return [
'date' => Carbon::parse($day['date']),
'high' => (float) $day['high'],
'low' => (float) $day['low'],
'condition' => $day['condition']
];
})
];
}
}
Метод fluent() значно підвищує якість коду, усуваючи повторення при конвертації типів, а також забезпечує безпечніший доступ до вкладених властивостей відповіді