Kritim Yantra
May 29, 2025
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.
Make sure you have the following before starting:
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.
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.
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;
}
}
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);
}
}
}
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');
});
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>
Run your server:
php artisan serve
Visit http://localhost:8000/gpt
, enter a prompt, and see the response from GPT-4!
To protect your app:
Use Laravelβs built-in throttle middleware:
Route::middleware('throttle:60,1')->post('/generate-response', [OpenAIController::class, 'generateResponse']);
Already handled in the controller using try-catch. You can log errors for further inspection if needed.
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
Consider using LaravelGPT if you need:
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!
Transform from beginner to Laravel expert with our personalized Coaching Class starting June 11, 2025. Limited enrollment ensures focused attention.
1-hour personalized coaching
Build portfolio applications
Industry-standard techniques
Interview prep & job guidance
Complete your application to secure your spot
Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google