How To Use OpenAI In Laravel 8/9

Websolutionstuff | Feb-06-2023 | Categories : Laravel

In this article, we will explore the integration of OpenAI into Laravel versions 8, 9, and 10. Our focus will be on understanding and utilizing the OpenAI API within Laravel applications. The OpenAI API is a versatile tool that can be employed for a wide range of tasks involving the comprehension and generation of natural language or code.

Additionally, we will introduce the openai-php/client package in Laravel 9 to facilitate your OpenAI integration. This article aims to provide you with practical insights on leveraging OpenAI's capabilities in your Laravel 8, 9, and 10 applications

OpenAI Build next-gen apps with OpenAI’s powerful models. OpenAI is a powerful artificial intelligence platform that allows developers to easily build AI-powered applications.

PHP Libraries:

So, let's see how to use OpenAI in laravel 8, how to use OpenAI in laravel 9, OpenAI PHP example, OpenAI laravel 9, OpenAI tutorial, and laravel OpenAI example.


 Step 1: Install laravel 9

In this step, we will install the laravel 9 application using the following composer command.

composer create-project laravel/laravel OpenAI-Example


Step 2: Install the OpenAI PHP Package

In this step, we will install the openai-php/client package using the following command. OpenAI PHP is a supercharged PHP API client that allows you to interact with the Open AI API.

Note: Requires PHP 8.1+

composer require openai-php/client


Step 3: Configure OpenAI

Now, we need the access key of OpenAI API. So, go to and click the signup button.

After signing up, go to and click the button Create new secret key.





Step 4: Create Routes

In this step, we create routes in the web.php file.



use Illuminate\Support\Facades\Route;

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!

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


Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('text/generate', [App\Http\Controllers\OpenAIController::class, 'index']);
Route::post('/generate', [App\Http\Controllers\OpenAIController::class, 'generateText']);


Step 5: Create Controller

In this step, we will create an OpenAIController.php file using the following command.

php artisan make:controller OpenAIController



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use OpenAI\Client;

class OpenAIController extends Controller
    public function index()
        return view('text_generate');

    public function generateText(Request $input){
        if ($input->title == null) {
        $title = $input->title;
        $client = OpenAI::client(env('OPENAI_API_KEY'));
        $result = $client->completions()->create([
            "model" => "text-davinci-003",
            "temperature" => 0.7,
            "top_p" => 1,
            "frequency_penalty" => 0,
            "presence_penalty" => 0,
            'max_tokens' => 600,
            'prompt' => sprintf('Write article about: %s', $title),
        $content = trim($result['choices'][0]['text']);

        return view('text_generate', compact('title', 'content'));



the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.


Step 6: Create Blade File

In this step, we will create a text_generate.blade.php file.


<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>How To Use OpenAI in Laravel 8/9 - Websolutionstuff</title>

        <!-- Fonts -->
        <link href=";600;700&display=swap" rel="stylesheet">

        <script src=""></script>

            body {
                font-family: 'Space Grotesk', sans-serif;
            .title:empty:before {


        <script src="" defer></script>

    <body class="antialiased">
        <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
            <div class="max-w-3xl w-full mx-auto sm:px-6 lg:px-8 space-y-4 py-4">
                <div class="text-center text-gray-800 dark:text-gray-300 py-4">
                    <h3 class="text-2xl font-bold">How To Use OpenAI in Laravel 8/9 - Websolutionstuff</h3>

                <div class="w-full rounded-md bg-white border-2 border-gray-600 p-4 min-h-[60px] h-full text-gray-600">
                    <form action="/generate" method="post" class="inline-flex gap-2 w-full">
                        <input required name="title" class="w-full outline-none text-2xl font-bold" placeholder="Enter an article title..." />
                        <button class="rounded-md bg-gray-500 px-4 py-2 text-white font-semibold">Generate</button>
                <div class="w-full rounded-md bg-white border-2 border-gray-600 p-4 min-h-[300px] h-full text-gray-600">
                    <textarea class="min-h-[300px] h-full w-full outline-none" spellcheck="false"></textarea>



Step 7: Run Laravel Application

Now, we will run how to use the OpenAI API in laravel 8 and laravel 9 using the following command.

php artisan serve


how_to_use_openai_ in_laravel


You might also like:

Recommended Post
Featured Post
Access Denied for user 'root'@'localhost' phpMyAdmin
Access Denied for user 'root'@...

phpMyAdmin is a valuable web-based tool for managing MySQL databases, simplifying various database tasks. However, runni...

Read More


Change Date Format Using Carbon In Laravel
Change Date Format Using Carbo...

In this article, we will see a change date format using carbon in laravel. Many times we have requirements to chang...

Read More


How to Use JSON Data Field in MySQL Database
How to Use JSON Data Field in...

Today, In this post we will see how to use json field in mysql database. In this tutorial i will give mysql json data ty...

Read More


Laravel 8 Ajax CRUD With Yajra Datatable
Laravel 8 Ajax CRUD With Yajra...

In this tutorial, we will see laravel 8 ajax crud with yajra datatable. I will show you how to create ajax crud ope...

Read More