Member-only story
How To Connect Laravel to ChatGPT API

Step 1: Create a new Laravel project
Assuming you have Laravel installed on your computer, create a new project by running the following command:
composer create-project laravel/laravel chatgpt
Step 2: Install Guzzle HTTP client
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and work with APIs. To install it, run the following command:
composer require guzzlehttp/guzzle
Step 3: Get an API key from ChatGPT
To use ChatGPT API, you need an API key. Visit https://beta.openai.com/docs/api-reference/introduction to sign up and get an API key.
Step 4: Create a new controller
In Laravel, controllers are used to handle HTTP requests and return responses. Create a new controller by running the following command:
php artisan make:controller ChatController
Step 5: Add a method to the controller to send a request to ChatGPT API
In the ChatController class, add a method that sends a request to ChatGPT API using Guzzle HTTP client. Here’s an example:
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
class ChatController extends Controller
{
public function chat(Request $request)
{
$client = new Client();
$response = $client->post('https://api.openai.com/v1/engine/davinci-codex/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . env('OPENAI_API_KEY'),
],
'json' => [
'prompt' => $request->input('message'),
'temperature' => 0.7,
'max_tokens' => 60,
'top_p' => 1,
'n' => 1,
'stop' => ['\n'],
],
]);
$result = json_decode($response->getBody()->getContents(), true);
return response()->json($result['choices'][0]['text']);
}
}