How to Integrate GPT-4 into Your Laravel SaaS Application

Author

Kritim Yantra

May 29, 2025

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!

LIVE MENTORSHIP ONLY 5 SPOTS

Laravel Mastery
Coaching Class Program

KritiMyantra

Transform from beginner to Laravel expert with our personalized Coaching Class starting June 11, 2025. Limited enrollment ensures focused attention.

Daily Sessions

1-hour personalized coaching

Real Projects

Build portfolio applications

Best Practices

Industry-standard techniques

Career Support

Interview prep & job guidance

Total Investment
$200
Duration
30 hours
1h/day

Enrollment Closes In

Days
Hours
Minutes
Seconds
Spots Available 5 of 10 remaining
Next cohort starts:
June 11, 2025

Join the Program

Complete your application to secure your spot

Application Submitted!

Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.

What happens next?

  • Confirmation email with program details
  • WhatsApp message from our team
  • Onboarding call to discuss your goals

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts