How to Integrate GPT-4 into Your Laravel SaaS Application
Integrating GPT-4 into your Laravel SaaS application can greatly enhance its capabilities by offering features like smart chatbots, content generation, summarization, and more. In this beginner-friendly guide, we’ll walk through the entire process of integrating OpenAI's GPT-4 into a Laravel 10+ application using the official PHP SDK.
🚪 Prerequisites
Make sure you have the following before starting:
- Laravel 10 or higher
- PHP 8.2+
- Composer installed
- An OpenAI API key (get it here)
⚙️ Step 1: Install the OpenAI Laravel Package
Open your terminal in the Laravel project directory and run:
composer require openai-php/laravel
Next, publish the config file:
php artisan openai:install
This will add a new config file: config/openai.php and update your .env file.
🔐 Step 2: Add Your OpenAI API Key
Open your .env file and add:
OPENAI_API_KEY=your-api-key-here
OPENAI_ORGANIZATION=your-org-id # Optional
Make sure config/openai.php references these values.
🧠 Step 3: Create a Service to Interact with OpenAI
Run the command to make a new service class:
php artisan make:service OpenAIService
In app/Services/OpenAIService.php, add the following:
<?php
namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;
class OpenAIService
{
public function generateChatResponse(string $prompt): string
{
$response = OpenAI::chat()->create([
'model' => 'gpt-4',
'messages' => [
['role' => 'user', 'content' => $prompt],
],
]);
return $response->choices[0]->message->content;
}
}
📝 Step 4: Create a Controller to Handle Requests
Run:
php artisan make:controller OpenAIController
Then edit app/Http/Controllers/OpenAIController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\OpenAIService;
class OpenAIController extends Controller
{
protected $openAIService;
public function __construct(OpenAIService $openAIService)
{
$this->openAIService = $openAIService;
}
public function generateResponse(Request $request)
{
$request->validate([
'prompt' => 'required|string',
]);
try {
$response = $this->openAIService->generateChatResponse($request->input('prompt'));
return response()->json(['response' => $response]);
} catch (\Exception $e) {
return response()->json(['error' => 'Something went wrong.'], 500);
}
}
}
🚧 Step 5: Add Routes
Open routes/web.php or routes/api.php and add:
use App\Http\Controllers\OpenAIController;
Route::post('/generate-response', [OpenAIController::class, 'generateResponse']);
Route::get('/gpt', function () {
return view('gpt');
});
🎨 Step 6: Build the Frontend
Create a Blade view: resources/views/gpt.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>GPT-4 Integration</title>
</head>
<body>
<h1>Ask GPT-4</h1>
<form id="gpt-form">
@csrf
<textarea name="prompt" id="prompt" rows="4" cols="50" placeholder="Enter your prompt here..."></textarea><br>
<button type="submit">Submit</button>
</form>
<div id="response"></div>
<script>
document.getElementById('gpt-form').addEventListener('submit', function(e) {
e.preventDefault();
fetch('/generate-response', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({
prompt: document.getElementById('prompt').value
})
})
.then(response => response.json())
.then(data => {
document.getElementById('response').innerText = data.response || data.error;
});
});
</script>
</body>
</html>
🚀 Step 7: Test Everything
Run your server:
php artisan serve
Visit http://localhost:8000/gpt, enter a prompt, and see the response from GPT-4!
🛡️ Step 8: Add Rate Limiting & Error Handling
To protect your app:
Rate Limiting
Use Laravel’s built-in throttle middleware:
Route::middleware('throttle:60,1')->post('/generate-response', [OpenAIController::class, 'generateResponse']);
Error Handling
Already handled in the controller using try-catch. You can log errors for further inspection if needed.
📊 Step 9: Write a Test
Generate a test file:
php artisan make:test OpenAIIntegrationTest
In tests/Feature/OpenAIIntegrationTest.php:
<?php
namespace Tests\Feature;
use Tests\TestCase;
class OpenAIIntegrationTest extends TestCase
{
/** @test */
public function it_returns_a_response_from_gpt()
{
$response = $this->postJson('/generate-response', [
'prompt' => 'Hello, GPT-4!'
]);
$response->assertStatus(200)
->assertJsonStructure(['response']);
}
}
Run your test:
php artisan test
🔄 Bonus: Use LaravelGPT for Advanced Use Cases
Consider using LaravelGPT if you need:
- Function calling
- Custom workflows
- Multi-turn conversations
✅ Conclusion
You’ve now successfully integrated GPT-4 into your Laravel SaaS application! With GPT-4, your app can offer intelligent, conversational capabilities and enhance user experience like never before.
Keep experimenting, monitor your usage, and build amazing things!
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.