In this guide, I’ll show you how to make HTTP requests using Guzzle in Laravel 12. Whether you're calling an external API, sending data, or getting a response, Guzzle makes it simple. I’ll walk through GET, POST, sending headers, and handling responses with clear code examples anyone can follow.
Laravel 12 Guzzle HTTP Request
Guzzle is a powerful PHP HTTP client included with Laravel. You can use it to make API calls like GET, POST, PUT, DELETE, etc., and handle the response in clean, simple syntax.
Laravel includes Guzzle by default, but if needed:
composer require guzzlehttp/guzzle
Example 1: Make a Simple GET Request
use Illuminate\Support\Facades\Http;
$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');
$data = $response->json(); // Get response as array
dd($data);
Example 2: Send a POST Request with Data
$response = Http::post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'Laravel Test',
'body' => 'This is a test post from Laravel 12.',
'userId' => 1
]);
$data = $response->json();
dd($data);
Example 3: Send Request with Headers
$response = Http::withHeaders([
'Authorization' => 'Bearer YOUR_API_TOKEN',
'Accept' => 'application/json',
])->get('https://api.example.com/user');
$data = $response->json();
dd($data);
Example 4: Post JSON Data
$response = Http::withHeaders([
'Content-Type' => 'application/json',
])->post('https://api.example.com/posts', [
'name' => 'Laravel',
'type' => 'framework',
]);
$data = $response->json();
Example 5: Add Timeout
$response = Http::timeout(5)->get('https://api.example.com/check');
Example 6: Handle Errors Gracefully
$response = Http::get('https://api.example.com/fail');
if ($response->successful()) {
return $response->json();
} elseif ($response->clientError()) {
return 'Client Error: ' . $response->status();
} elseif ($response->serverError()) {
return 'Server Error: ' . $response->status();
}
Using Guzzle Client Directly
You can also use the native Guzzle client:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'https://api.example.com/data');
$data = json_decode($response->getBody(), true);
dd($data);
You might also like: