- Published on
Laravel OpenAI database queries
Thanks to BeyondCode, we're now able to query our Laravel database using natural english!
OpenAI Part
OpenAI Account
Sign up with OpenAi or Login if you already have an account.
Create a new API key
After creating or logging in into your account, you can now click on your profile name (Named Personal by default) and it should be found in the bottom left corner of the website. Then navigate to "View API keys" and click on "+ Create new secret key". Don't forget to copy the key when you create it because you can only see it one time.
Laravel Part
Setting Up the Package
Ofcourse, we'll have to install a laravel project or use an exsisting one. Please check my article about (Installing Laravel with VueJS)[/posts/install-laravel-vuejs].
We will use beyondcode's package to make everything smooth!
composer require beyondcode/laravel-ask-database
After that, we can publish the configuration
php artisan vendor:publish --tag="ask-databse-config"
In our env file, we should add
OPENAI_API_KEY=sk-...
PHP curl
Certificate
PHP 5.6^ needs a certificate to use cURL. To download the certificate, visit curl.se and get the bundle.
Move cacert.pem to your PHP directory (e.g: usr/local/etc/php/8.1) and change the php.ini curl.cainfo
and openssl.cafile
to have your certificate file path.
For more information, please check this stackoverflow Q/A.
Using Natural Language
Now, we're ready to query the database using natural language!
DB::ask('What is the name of my our first user?');
To make it more fancy, we just add an input tag to our front-end and ask the user to prompt any question! then move that question and query it!.
<input name='question' type='text' class='bla-bla' />
DB::ask($request->question);
and voila! Happy coding!
If you find my content useful, please follow me on Github or Twitter