Integrating AI into your applications is essential for creating smart, interactive experiences. In this blog, we explain how to use the ChatGPT API with Laravel. You ll get a step-by-step guide from setup to building a chat-like application with AI features.
Whether you are a Laravel developer or exploring AI, this guide makes ChatGPT integration simple. Follow it to add intelligent interactions and enhance your projects.
Why Integrate ChatGPT in Laravel?
Advanced AI-driven features like conversational interfaces, automated responses, and natural language understanding are made possible by integrating ChatGPT in Laravel application.
By enabling dynamic and context-aware communication, decreasing manual labor, and increasing engagement, ChatGPT improves the user experience. By combining ChatGPT s AI capabilities with Laravel s powerful backend, developers can build intelligent applications faster. This synergy drives innovation and delivers solutions that add value across a wide range of industries.
Generating an OpenAI API Key for ChatGPT
Before starting, you need to generate API key from OpenAI for accessing AI models. Our detailed blog post on this topic walks you through the simple process of creating a new API key securely on the OpenAI platform.
This key is essential for authenticating your Laravel application s requests to the ChatGPT API. For step-by-step instructions and helpful visuals, refer to our comprehensive guide at How to Generate an OpenAI API Key for ChatGPT Integration.
Install OpenAI package
For seamless ChatGPT integration into your Laravel application, we recommended to use OpenAI’s official PHP package. Built specifically for PHP, this package simplifies communication with the OpenAI API, eliminating the need to manage raw HTTP requests manually.
Start by installing the official OpenAI PHP SDK via Composer with this command:
composer require php-openai/openai
Once installed, you can utilize openai package to perform API request and ChatGPT operations.
Configuring ChatGPT API key
Before building the full interface for your AI chat system, you must first configure your OpenAI API key in your application. This key allows the openai
package to authenticate your account and perform all necessary operations securely.
Add this key into your environment file.
OPENAI_API_KEY=your_openai_api_key_here
Open services.php from config directory and add below code into it:
'openai' => [
'api_key' => env('OPENAI_API_KEY'),
],
ChatGPT API integration in Laravel
Let’s take an example something like any other AI chat application where user post their query and response will shown as per their requirements. In this example, we will create a simple conversion screen which relays on ChatGPT’s APIs via it’s key.
Let’s define few routes for our implementation. Open web.php and modify it as below:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChatController;
Route::get('/chat', [ChatController::class, 'showChat']);
Route::post('/chat', [ChatController::class, 'sendMessage']);
To display the chat interface to users, you need to create a Blade view file in Laravel s resources/views directory.
Create a new file named chat.blade.php and add basic HTML to structure the chat view. This includes a container element where chat messages will appear, styled message blocks to distinguish user and AI messages, and a form with a text input and submit button for sending messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Laravel ChatGPT Chat</title>
<style>
body { font-family: Arial, sans-serif; margin: 2rem; }
#chat-box { border: 1px solid #ccc; height: 400px; overflow-y: auto; padding: 1rem; }
.message { margin-bottom: 1rem; }
.user { color: blue; }
.bot { color: green; }
input[type=text] { width: 80%; padding: 0.5rem; }
button { padding: 0.5rem 1rem; }
</style>
</head>
<body>
<h1>Laravel ChatGPT Chat</h1>
<div id="chat-box"></div>
<form id="chat-form">
<input type="text" id="message-input" autocomplete="off" placeholder="Type your message" required />
<button type="submit">Send</button>
</form>
<script>
const chatBox = document.getElementById('chat-box');
const form = document.getElementById('chat-form');
const input = document.getElementById('message-input');
function appendMessage(text, sender) {
const msgDiv = document.createElement('div');
msgDiv.className = 'message ' + sender;
msgDiv.textContent = text;
chatBox.appendChild(msgDiv);
chatBox.scrollTop = chatBox.scrollHeight;
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const message = input.value.trim();
if (!message) return;
appendMessage(message, 'user');
input.value = '';
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ message })
});
const data = await response.json();
appendMessage(data.reply, 'bot');
});
</script>
</body>
</html>
It will handle user input and make ajax call to our application. Based on user’s query it will call OpenAI package and return JSON response to frontend.
Create a service class ChatGPTService.php to encapsulate communication with OpenAI API:
<?php
namespace App\Services;
use OpenAI;
class ChatGPTService
{
protected \OpenAI\Client $client;
public function __construct()
{
$this->client = OpenAI::factory()
->withApiKey(config('services.openai.api_key'))
->make();
}
public function chat(string $prompt): string
{
$response = $this->client->chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'user', 'content' => $prompt],
],
]);
return $response->choices[0]->message->content ?? 'No response';
}
}
In this service class it will initialize client of OpenAI and provide it to class. The chat method will handle API call for ChatGPT and return string as function response. you will utilize this service class into your controller or other portion of application. It can be reused anywhere into application.
For handling user input and response, you need controller logic. Create new controller using below command:
php artisan make:controller ChatController
It will create ChatController into controller directory. Let’s modify it as per our requirements:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\ChatGPTService;
class ChatController extends Controller
{
protected ChatGPTService $chatGPT;
public function __construct(ChatGPTService $chatGPT)
{
$this->chatGPT = $chatGPT;
}
// GET: Show Chat page
public function showChat()
{
return view('chat');
}
// POST: Process user message and return ChatGPT response
public function sendMessage(Request $request)
{
$request->validate([
'message' => 'required|string',
]);
$reply = $this->chatGPT->chat($request->message);
return response()->json(['reply' => $reply]);
}
}
This controller will handle logic for showing our chat screen and perform request to OpenAI and return it to the front-end.
This complete example demonstrates Laravel ChatGPT integration using the official OpenAI PHP package, with backend API communication and a chat interface frontend ready for smart AI features.
Conclusion
Using ChatGPT API in Laravel for smart AI features enhances your app’s interactivity and intelligence. The OpenAI package simplifies API communication, enabling clean and reliable Laravel ChatGPT setup and integration. With this guide, you can build powerful AI-powered chat applications that improve user engagement and automate conversations with ease.