Navigation

Laravel

How to Send `x-www-form-urlencoded` Data with the HTTP Client

Send form-urlencoded data with Laravel HTTP client in 2025. Perfect for legacy APIs and third-party integrations that require traditional form submissions.

Table Of Contents

Quick Fix: The asForm() Method

Many APIs still expect the old-school application/x-www-form-urlencoded format instead of JSON. Laravel 9+ makes this simple:

use Illuminate\Support\Facades\Http;

// Send form-encoded data (Laravel 9+)
$response = Http::asForm()->post('https://api.example.com/webhook', [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'message' => 'Hello from Laravel!'
]);

// With authentication
$response = Http::asForm()
    ->withToken('your-api-token')
    ->post('https://api.payment.com/process', [
        'amount' => 1000,
        'currency' => 'USD',
        'customer_id' => '12345'
    ]);

For Laravel 8 and older versions:

// Manual content-type header approach
$response = Http::withHeaders([
    'Content-Type' => 'application/x-www-form-urlencoded',
])
->post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2'
]);

// Or use the attach method for complex forms
$response = Http::attach(
    'document', file_get_contents('/path/to/file.pdf'), 'document.pdf'
)->post('https://api.example.com/upload', [
    'user_id' => 123,
    'category' => 'invoices'
]);

Laravel Version Compatibility

The asForm() method was introduced in Laravel 9.0. For earlier versions, you'll need to manually set the Content-Type header. This method automatically handles encoding arrays and special characters, preventing common submission errors like "Invalid request format" or "Malformed data" that developers often encounter.

Real-world example with error handling:

try {
    $response = Http::timeout(30)
        ->asForm()
        ->post('https://legacy-api.com/users', [
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email_address' => $user->email, // Note different field names
        ]);
        
    if ($response->successful()) {
        return $response->json();
    }
    
    Log::error('Form submission failed', [
        'status' => $response->status(),
        'body' => $response->body()
    ]);
    
} catch (\Illuminate\Http\Client\RequestException $e) {
    // Handle connection errors, timeouts
    throw new ApiException('External service unavailable: ' . $e->getMessage());
}

Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Building Multi-tenant Applications with Laravel: A Comprehensive Guide | REST API Design Best Practices Tutorial 2025 | Complete Guide to JSON Handling in PHP: Performance & Security Best Practices 2025

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel