search
HomePHP FrameworkLaravelTeach you step by step how to use ChatGPT in Laravel10 project

This article brings you relevant knowledge about Laravel, which mainly introduces how to use ChatGPT in the Laravel10 project? For those who are interested, take a look below, I hope it will be helpful to you.

Use ChatGPT in your Laravel 10 project!

What you get

Teach you step by step how to use ChatGPT in Laravel10 project

Teach you step by step how to use ChatGPT in Laravel10 project

##I assume you have used the official documentation Installed the Laravel 10 framework

Step 1: Create a controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class ChatGPTController extends Controller
{
    public function index()
    {
        return view(&#39;chatgpt.index&#39;);
    }
    public function ask(Request $request)
    {
        $prompt = $request->input(&#39;prompt&#39;);
        $response = $this->askToChatGPT($prompt);
        return view(&#39;chatgpt.response&#39;, [&#39;response&#39; => $response]);
    }
    private function askToChatGPT($prompt) 
    {
        $response = Http::withoutVerifying()
            ->withHeaders([
                &#39;Authorization&#39; => &#39;Bearer &#39; . env(&#39;CHATGPT_API_KEY&#39;),
                &#39;Content-Type&#39; => &#39;application/json&#39;,
            ])->post(&#39;https://api.openai.com/v1/engines/text-davinci-003/completions&#39;, [
                "prompt" => $prompt,
                "max_tokens" => 1000,
                "temperature" => 0.5
            ]);
        return $response->json()[&#39;choices&#39;][0][&#39;text&#39;];
    }
}

Step 2: Create a route

<?php
use App\Http\Controllers\ChatGPTController;
use Illuminate\Support\Facades\Route;
(...)
Route::get(&#39;/chatgpt&#39;, [ChatGPTController::class, &#39;index&#39;])
    ->name(&#39;chatgpt.index&#39;);
Route::post(&#39;/chatgpt/ask&#39;, [ChatG²PTController::class, &#39;ask&#39;])
    ->name(&#39;chatgpt.ask&#39;);

Step 3: Create a layout

// 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(&#39;css/app.css&#39;) }}" 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(&#39;content&#39;)
        </div>
    </body>
</html>

Step 4: Create index page

// chatgpt/index.blade.php
@extends(&#39;layouts.app&#39;)
@section(&#39;content&#39;)
    <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(&#39;chatgpt.ask&#39;) }}">
                            @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 page

// chatgpt/response.blade.php
@extends(&#39;layouts.app&#39;)
@section(&#39;content&#39;)
    <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

Finally step 6: Create a .env variable

CHATGPT_API_KEY=YOUR_API_KEY

Get ChatGPT API Key

To obtain the API key you can go to the api-keys section in your openai platform account and generate your key

Teach you step by step how to use ChatGPT in Laravel10 project

If you want more examples, you can go to the official examples section: platform.openai.com/examples

Recommended learning: "

laravel video tutorial"

The above is the detailed content of Teach you step by step how to use ChatGPT in Laravel10 project. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Last Laravel version: Migration TutorialLast Laravel version: Migration TutorialMay 14, 2025 am 12:17 AM

What new features and best practices does Laravel's migration system offer in the latest version? 1. Added nullableMorphs() for polymorphic relationships. 2. The after() method is introduced to specify the column order. 3. Emphasize handling of foreign key constraints to avoid orphaned records. 4. It is recommended to optimize performance, such as adding indexes appropriately. 5. Advocate the idempotence of migration and the use of descriptive names.

What is the Latest LTS Version of Laravel?What is the Latest LTS Version of Laravel?May 14, 2025 am 12:14 AM

Laravel10,releasedinFebruary2023,isthelatestLTSversion,supportedforthreeyears.ItrequiresPHP8.1 ,enhancesLaravelPennantforfeatureflags,improveserrorhandling,refinesdocumentation,andoptimizesperformance,particularlyinEloquentORM.

Stay Updated: The Newest Features in the Latest Laravel VersionStay Updated: The Newest Features in the Latest Laravel VersionMay 14, 2025 am 12:10 AM

Laravel's latest version introduces multiple new features: 1. LaravelPennant is used to manage function flags, allowing new features to be released in stages; 2. LaravelReverb simplifies the implementation of real-time functions, such as real-time comments; 3. LaravelVite accelerates the front-end construction process; 4. The new model factory system enhances the creation of test data; 5. Improves the error handling mechanism and provides more flexible error page customization options.

Implementing Soft Delete in Laravel: A Step-by-Step TutorialImplementing Soft Delete in Laravel: A Step-by-Step TutorialMay 14, 2025 am 12:02 AM

Softleteinelelavelisling -Memptry-braceChortsDevetus -TeedeecetovedinglyDeveledTeecetteecedelave

Current Laravel Version: Check the Latest Release and UpdatesCurrent Laravel Version: Check the Latest Release and UpdatesMay 14, 2025 am 12:01 AM

Laravel10.xisthecurrentversion,offeringnewfeatureslikeenumsupportinEloquentmodelsandimprovedroutemodelbindingwithenums.Theseupdatesenhancecodereadabilityandsecurity,butrequirecarefulplanningandincrementalimplementationforasuccessfulupgrade.

How to Use Laravel Migrations: A Step-by-Step TutorialHow to Use Laravel Migrations: A Step-by-Step TutorialMay 13, 2025 am 12:15 AM

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

Finding the Latest Laravel Version: A Quick and Easy GuideFinding the Latest Laravel Version: A Quick and Easy GuideMay 13, 2025 am 12:13 AM

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

Staying Updated with Laravel: Benefits of Using the Latest VersionStaying Updated with Laravel: Benefits of Using the Latest VersionMay 13, 2025 am 12:08 AM

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools