Got an Email Template, Landing page, or Banner requirement? Head to Email Mavlers

back arrow
All Blogs
ChatGPT with Laravel

The Ultimate Guide to ChatGPT Integration in Laravel (With Code Examples!)

If you want to learn Laravel ChatGPT integration intricacies in a simple way, then this is the place to be!...

So, you are a web dev expert who would like your Laravel app to think, respond intelligently, and even converse like a human. 

What if you could build a chatbot that understands user queries, automates responses with AI, or generates content dynamically—all without writing thousands of lines of logic? Sounds exciting, right?

That’s exactly what you’ll achieve by integrating ChatGPT with Laravel.

With over 15+ years of experience and 9K+ websites developed, we at Mavlers have the requisite experience and expertise to help you seamlessly integrate ChatGPT with Laravel. 

In today’s blog, Hardik Kotak, our in-house web dev expert, will walk you through a beginner-friendly yet powerful way to:

✅ Set up Laravel to communicate with ChatGPT

✅ Use a dedicated service class for clean API calls

✅ Create a user-friendly frontend with AJAX for real-time AI responses

By the end, you won’t just know how to integrate ChatGPT—you’ll have a fully functional AI-powered Laravel application that can generate responses dynamically.

Let’s dive in and bring AI into your Laravel project today! 🚀

Source (Yep, we kinda ate and left no crumbs! 😉 )

1. Setting up your Laravel project

Before we jump into AI magic, let’s set up our Laravel environment. Run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel chatgpt-laravel

This command will create a new folder, chatgpt-laravel, and install all the necessary Laravel dependencies. Once the setup is done and dusted, navigate into the project directory using the following:

cd chatgpt-laravel

Now, let’s get our API integration ready!

2. Installing dependencies for API calls

To establish communication with the ChatGPT API, we need a robust HTTP client. 

Laravel provides an excellent option called Guzzle—a popular PHP library for handling API requests. It simplifies the process of integrating third-party libraries into your PHP applications.

You may install it using:

composer require guzzlehttp/guzzle

With Guzzle set up, we’re ready to retrieve our API credentials.

3. Get your ChatGPT API credentials

To connect with OpenAI’s API, you’ll need an API key. If you haven’t already, follow these steps:

  1. Sign Up at OpenAI’s website.
  2. Log in and navigate to the API Section in your dashboard.
  3. Create an API Key and copy it somewhere safe—you won’t be able to view it again later!

Once you have your API key, open your Laravel .env file and add the following line:

ChatGPT_API_KEY=your_openai_api_key_here

Now, let’s build a service class to interact with ChatGPT.

4. Creating a ChatGPT service class

The best way to manage API interactions in Laravel is by using a service class. This keeps your code clean and modular.

You can follow the following steps to create a service class:

  1. Inside the app/ directory, create a new folder named Services (if it doesn’t already exist).
  2. Inside app/Services/, create a new file called ChatGPTService.php.
  3. Add the following code to handle API requests:
<?php
namespace App\Services;
use GuzzleHttp\Client;

class ChatGPTService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => 'https://api.openai.com/v1/',
        ]);
    }

    public function generateText($prompt)
    {
        $response = $this->client->post('chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . env('ChatGPT_API_KEY'),
            ],
            'json'    => [
                'model'      => 'gpt-3.5-turbo',
                'messages' => [
                    ['role' => 'system', 'content' => 'You are a helpful assistant.'],
                    ['role' => 'user', 'content' => $prompt],
                ],
                'max_tokens' => 150,
            ],
        ]);

        $body = json_decode($response->getBody(), true);
        return $body['choices'][0]['message']['content'] ?? '';
    }
}

Now, our Laravel app can interact with ChatGPT! Next, let’s create a controller to handle user input and fetch responses.

5. Creating a controller for ChatGPT

Now that our service is ready, we need a controller to connect it with our Laravel routes and handle user requests.

We recommend the following steps to create the controller:

  1. Run the following command to generate a controller:
php artisan make:controller ChatGPTController

2. Open app/Http/Controllers/ChatGPTController.php and add the following code:

<?php
namespace App\Http\Controllers;

use App\Services\ChatGPTService;
use Illuminate\Http\Request;

class ChatGPTController extends Controller
{
    protected $ChatGPT;

    public function __construct(ChatGPTService $ChatGPT)
    {
        $this->ChatGPT = $ChatGPT;
    }

    public function generateTextAjax(Request $request)
    {
        $request->validate([
            'prompt' => 'required|string|max:1000',
        ]);

        $prompt = $request->input('prompt');

        try {
            $response = $this->ChatGPT->generateText($prompt);

            return response()->json([
                'generated_text' => $response,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to generate text. Please try again.',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }
}

This controller helps you with the following:

✅ Validates user input before sending it to the API.

✅ Calls the ChatGPT service to generate a response.

✅ Returns the response as JSON for use in an AJAX call.

Now, let’s connect everything with a simple front end!

6. Creating a Blade template with AJAX

To make the interaction seamless, let’s create a basic Blade template and use AJAX to send user input.

Here are the steps you may implement to create the view:

  1. Inside the resources/views directory, create a file called chat.blade.php.

2. Add the following HTML and JavaScript code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChatGPT Laravel Integration</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Chat with AI</h2>
    <textarea id="userPrompt" placeholder="Type your message..."></textarea>
    <button id="sendPrompt">Send</button>
    <p><strong>Response:</strong> <span id="responseText"></span></p>

    <script>
        $(document).ready(function () {
            $('#sendPrompt').click(function () {
                var userPrompt = $('#userPrompt').val();

                $.ajax({
                    url: "{{ route('chat.generate') }}",
                    type: "POST",
                    data: { prompt: userPrompt, _token: "{{ csrf_token() }}" },
                    success: function (response) {
                        $('#responseText').text(response.generated_text);
                    },
                    error: function () {
                        $('#responseText').text("Error fetching response.");
                    }
                });
            });
        });
    </script>
</body>
</html>

Now, add a route for this in routes/web.php:

use App\Http\Controllers\ChatGPTController;

Route::get('/chat', function () {
    return view('chat');
});

Route::post('/chat/generate', [ChatGPTController::class, 'generateTextAjax'])->name('chat.generate');

The road ahead 

On that note, you have successfully learned to integrate ChatGPT with Laravel. You might now want to read about the latest developments in Laravel 12.

Did you like this post? Do share it!
Hardik Kotak

Hardik is a seasoned Subject Matter Expert (SME) and Team Lead at Mavlers, with over 13 years of experience in the tech industry. With a strong background in full-stack web application development, he specializes in using Laravel, HTML, CSS (Bootstrap), and PHP to create robust solutions. His expertise also extends to developing APIs for mobile applications and managing server infrastructure on AWS.

Naina Sandhir - Content Writer

A content writer at Mavlers, Naina pens quirky, inimitable, and damn relatable content after an in-depth and critical dissection of the topic in question. When not hiking across the Himalayas, she can be found buried in a book with spectacles dangling off her nose!

Leave a reply

Your email address will not be published. Required fields are marked *

Tell us about your requirement

We’ll get back to you within a few hours!