Using ChatGPT in a Laravel 10 project
Tags: laravel, chatgpt, ai
Published: 2023-02-20 21:55:31

![chatgpt and laravel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trs5rgiguin2sdyb33r9.png)

**This tutorial explains how to use ChatGPT in a Laravel 10 project.**

I will try to be clear and concise 😃

## What you will get

![form to ask something to chatgpt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7wjvqgv5sp2cjv76gbk.png)

![chatgpt answer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0crw23guqjuji9mg328.png)

## Setup
I'm supposing you already installed the Laravel 10 framework, using the [official documentation](https://laravel.com/docs/10.x)

## Step 1: create controller 
```php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ChatGPTController extends Controller
{
    public function index()
    {
        return view('chatgpt.index');
    }

    public function ask(Request $request)
    {
        $prompt = $request->input('prompt');
        $response = $this->askToChatGPT($prompt);

        return view('chatgpt.response', ['response' => $response]);
    }

    private function askToChatGPT($prompt) 
    {
        $response = Http::withoutVerifying()
            ->withHeaders([
                'Authorization' => 'Bearer ' . env('CHATGPT_API_KEY'),
                'Content-Type' => 'application/json',
            ])->post('https://api.openai.com/v1/engines/text-davinci-003/completions', [
                "prompt" => $prompt,
                "max_tokens" => 1000,
                "temperature" => 0.5
            ]);

        return $response->json()['choices'][0]['text'];
    }
}
```

## Step 2: create routes
```php
<?php
use App\Http\Controllers\ChatGPTController;
use Illuminate\Support\Facades\Route;

(...)
Route::get('/chatgpt', [ChatGPTController::class, 'index'])
    ->name('chatgpt.index');
Route::post('/chatgpt/ask', [ChatG²PTController::class, 'ask'])
    ->name('chatgpt.ask');
```

## Step 3: create layout
```php
// layouts/app.blade.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>My ChatGPT App</title>

        <!-- Styles -->
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container mt-5">
            @yield('content')
        </div>
    </body>
</html>
```

## Step 4: create index view
```php
// chatgpt/index.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Ask something to ChatGPT</div>

                    <div class="card-body">
                        <form method="POST" action="{{ route('chatgpt.ask') }}">
                            @csrf

                            <div class="form-group">
                                <input type="text" class="form-control text-center" name="prompt" placeholder="Ask something...">
                            </div>

                            <button type="submit" class="btn btn-primary">Send</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
```

## Step 5: create response view
```php
// chatgpt/response.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">ChatGPT answer</div>

                    <div class="card-body">
                        <p>{{ $response }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
```

## Final step 6: create a .env variable
```bash
CHATGPT_API_KEY=YOUR_API_KEY
```

## Get the ChatGPT API key
To get the API key, you can go to [api-keys section in your openai platform account](https://platform.openai.com/account/api-keys) and generate your key

![how generate chatgpt api key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36jpe6tfsrp8jruy2pa7.png)

## The final word 💬
Thanks for reading this little tutorial, feel free to add a comment to share your opinions! 😀☕

If you want the project I created for this tutorial, feel free to go on the [repository](https://github.com/Jerome-W-90/chatgpt-laravel)

If you want more examples, you can go to the official example section : [https://platform.openai.com/examples](https://platform.openai.com/examples)