Laravel 11 - Gemini API PHP Client
Laravel 11 - Gemini API PHP Client
In this tutorial, we will explore how to integrate the Gemini API PHP client into Laravel 11, enabling dynamic content generation, which can enhance user interaction.
If you're a video person, feel free to skip the post and check out the video instead!
Step # 1 : Create fresh Laravel project or use existing project.
Two commands to create fresh laravel project.
Global Command : laravel new gemini
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist gemini
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/gemini
Step # 3 : Install the package.
Run the following command to install the package.
Command : composer require gemini-api-php/client
Step # 4 : Obtain the Google AI Studio API Key.
Go to Google Cloud Platform.
Link : https://console.cloud.google.com/welcome?project
If you're not already signed in, use your Google account credentials to log in.
Click on Select a Project at the top of the page and then choose New Project to create a project for testing purposes. Give it a suitable name.
Go to Google AI Studio.
Link : https://aistudio.google.com/app/apikey
Click on Get API key and then click Create API key.
Select the testing project that we just created.
Click on Create API key in existing project.
Copy and save the API key.
Step # 5 : Define the API key.
Open the .env file in your Laravel project. Add the following line to define the API key.
GEMINI_API_KEY="Define_Your_API_Key_Here"
Replace Define_Your_API_Key_Here with the actual API key you copied.
Step # 6 : Update view.
Let's replace the default welcome.blade.php file with a basic HTML form that contains an input field where users can ask questions to Gemini. We'll use AJAX to submit the form, and dynamically append the questions and answers to the chat area.
<!DOCTYPE html>
<html>
<head>
<title>Laravel - Gemini Integration - Code Shotcut</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- CSRF token for secure AJAX requests -->
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<!-- Main container to center the form and chat window -->
<div class="container mx-auto px-4 h-screen flex flex-col items-center justify-start pt-6">
<!-- Form to ask questions -->
<form id="ask" class="bg-gray-800 rounded-lg p-8 w-full max-w-3xl mb-6">
<h1 class="text-2xl font-bold text-white mb-4 text-center">Laravel - Gemini</h1>
<div class="mb-4">
<label class="block text-white text-sm font-bold mb-2" for="question">
Have a question? Ask Gemini
</label>
<!-- Input field for entering the question -->
<input class="border border-gray-600 appearance-none rounded w-full py-2 px-3 text-gray-900 leading-tight focus:outline-none focus:shadow-outline" id="question" name="question" type="text" placeholder="Ask Gemini">
<div class="text-red-500 text-sm mt-2" id="question_help"></div>
</div>
<div class="flex items-center justify-center">
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit">
Ask
</button>
</div>
</form>
<!-- Chat area to display questions and answers -->
<div class="container mx-auto px-4 mt-6 w-full max-w-3xl" id="chat"></div>
</div>
<!-- jQuery for handling AJAX requests -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
// Setup CSRF token for AJAX
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
// Clear the chat div when the page loads
$('#chat').html('');
});
// Base URL for API requests
let baseUrl = {!! json_encode(url('/')) !!};
// Form submission handling
$('#ask').submit(function(event) {
// Prevent default form submission
event.preventDefault();
// Get form element
let form = $('#ask')[0];
// Collect form data
let formData = new FormData(form);
// AJAX request to submit the question
$.ajax({
url: baseUrl + '/question', // Endpoint to send the question
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
// Clear error messages
refresh();
// Create question and answer divs
let divQuestion = `<div class="bg-gray-800 text-white rounded p-4 mb-4"><h4 class="font-bold">Question: ${data.question}</h4></div>`;
let divAnswer = `<div class="bg-gray-800 text-white rounded p-4 mb-4"><h5 class="font-bold">Answer</h5><textarea class="w-full h-32 p-2 border border-gray-600 rounded bg-gray-900 text-white" readonly>${data.answer}</textarea></div>`;
// Append the question and answer to the chat div
$('#chat').append(divQuestion);
$('#chat').append(divAnswer);
},
error: function(reject) {
refresh(); // Clear error messages
if (reject.status === 422) {
// Validation error handling
let errors = $.parseJSON(reject.responseText);
// Display the validation errors
$.each(errors.errors, function(key, value) {
$('#' + key + '_help').text(value[0]);
});
}
}
});
});
// Function to clear error messages
function refresh() {
$('#question_help').text('');
}
</script>
</body>
</html>
Step # 7 : Create a controller.
To create the controller, run the following Artisan command.
Command : php artisan make:controller GeminiController
After creating the controller, update the GeminiController like below.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GeminiAPI\Client;
use GeminiAPI\Resources\Parts\TextPart;
class GeminiController extends Controller
{
public function index(Request $request)
{
$request->validate([
'question' => 'required',
]);
$question = $request->question;
// Initialize the Gemini API client with the API key from the .env file
$client = new Client(env('GEMINI_API_KEY'));
// Use the Gemini API to generate a response for the question
$response = $client->geminiPro()->generateContent(
new TextPart($question),
);
// Extract the answer from the API response
$answer = $response->text();
// Return the question and the generated answer as a JSON response
return response()->json(['question' => $question, 'answer' => $answer]);
}
}
Step # 8 : Define a route.
Import GeminiController class and create a route.
use App\Http\Controllers\GeminiController;
// To display the view
Route::get('/gem', function () {
return view('gemini');
});
// Handle form submission.
Route::post('/question', [GeminiController::class, 'index']);
Step # 9 : It's time to test.
Start the Laravel development server.
Command : php artisan serve.
Access below URL
127.0.0.1:8000
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments