Laravel Tutorials

Using Laravel's fluent Method for HTTP Response Transformations

Published
Using Laravel's fluent Method for HTTP Response Transformations image

Laravel enhances API interactions with the new fluent() method on HTTP Client responses. This feature provides type-safe access to response data, streamlining how you work with external APIs.

The method converts responses into fluent objects with type-specific accessors:

$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

Here's an implementation in a weather forecasting service:

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']
                ];
            })
        ];
    }
}

The fluent() method greatly improves code quality by eliminating type conversion boilerplate while providing safer access to nested response properties.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Session Replay for Laravel: Self-Hosted Browser Recordings image

Session Replay for Laravel: Self-Hosted Browser Recordings

Read article
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article