Laravel 11 - Gemini API PHP Client

Touseef Afridi
17 Sep 24

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!


Quick Overview

This guide walks you through integrating the Gemini API with Laravel, starting from setting up a new Laravel project with MySQL and Pest for testing. After installing the Gemini API client and configuring your API key, a simple front-end interface is created for users to submit questions and receive real-time answers. A controller is set up to handle the logic and process API requests, while routes connect the front-end to the back-end. Finally, the Laravel server is started, allowing you to test the app and interact with Gemini for AI-powered responses.

Step # 1 : Set Up a New Laravel Project.

We can either create a fresh Laravel project or use an existing one. If Laravel is installed globally, run.
laravel new gemini
Or, use Composer.
composer create-project laravel/laravel --prefer-dist gemini
During setup, make the following selections to align with our development stack:
  • Starter Kit: Choose None.
  • Testing Framework: Select Pest.
  • Database: Choose MySQL.
  • Run Migrations: Type yes to run the default migrations.

This sets up a minimal Laravel installation with Pest for testing and MySQL as the database, ready for further development.

Step # 2 : Access the Laravel Project Directory.

Use a terminal (such as Git Bash or Command Prompt) to navigate to the root folder of your Laravel project.
cd c:xampp/htdocs/gemini
This step ensures you're working inside the correct project directory where all Laravel commands and development tasks will be executed.

Step # 3 : Install the Gemini API Client Package.

Install the required Gemini API PHP client package using Composer.
composer require gemini-api-php/client
This command pulls the Gemini API client library into your Laravel project, allowing us to interact with the Gemini services through clean, PHP-based methods.

Step # 4 : Get Your Google AI Studio API Key.

To generate your API key, follow these steps
  1. Visit the Google Cloud Console: https://console.cloud.google.com/welcome?project
  2. Sign in with your Google account if you're not already logged in.
  3. At the top, click Select a project, then choose New Project to create one for testing. Give it a descriptive name.
  4. Go to Google AI Studio: https://aistudio.google.com/app/apikey
  5. Click Get API key, then choose Create API key.
  6. When prompted, select the project you just created.
  7. Click Create API key in existing project.
  8. Copy and securely save the generated API key you’ll need it in the next steps.

This key allows your Laravel application to authenticate and interact with Google's AI services via the Gemini API.

Step # 5 : Configure the Gemini API Key in Your Environment.

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 from Google AI Studio.

Step # 6 : Create the User Interface for Asking Questions.

To interact with the Gemini API, we’ll update the default welcome.blade.php file with a simple and responsive interface. This view will include a form where users can type their questions, submit them using AJAX, and see responses displayed instantly in a chat-style layout. The form uses Tailwind CSS for styling and jQuery for handling asynchronous requests. Each submitted question and its corresponding answer from the Gemini API will be appended to a chat container, providing a dynamic and seamless user experience without requiring a page refresh. Here’s the updated code for the view.
<!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>
With this simple interface in place, users can type a question, hit the Ask button, and instantly see Gemini’s response appear right below just like chatting with an AI assistant in real time.

Step # 7 : Create the Gemini Controller.

Now that our front-end is ready, let’s build the backend logic to handle user questions and fetch answers from the Gemini API. Start by generating a new controller using Artisan.
php artisan make:controller GeminiController
This will create a file called GeminiController.php in the app/Http/Controllers directory. Open that file and update it with the following logic.
<?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]);
    }
}
The index method receives the user's question, sends it to the Gemini API for processing, and returns the AI-generated response all in real time.

Step # 8 : Define a route.

To connect the frontend with the backend logic, we need to define routes that handle both displaying the view and processing the form submissions. Here's how to set it up. First, import the GeminiController class at the top of your routes/web.php file.
use App\Http\Controllers\GeminiController;
Now, define the routes.
// To display the view
Route::get('/gem', function () {
    return view('gemini');
});
// Handle form submission.
Route::post('/question', [GeminiController::class, 'index']);
The first route serves the view (/gem) that users will interact with, while the second route (/question) handles the form submission. When a user submits a question, the form sends a POST request to this route, triggering the index method in the GeminiController to process the question and fetch the answer.

Step # 9 : It's time to test.

Now that everything is set up, it’s time to test the functionality. Start the Laravel development server by running the following command in your terminal.
php artisan serve
Once the server is running, open your browser and go to the following URL: 127.0.0.1:8000.

Now you can interact with the application, submit questions, and receive real-time answers from the Gemini API.

Conclusion

By following this guide, you've successfully integrated the Gemini API into your Laravel application, enabling real-time AI-powered responses to user questions. With the Gemini API connected, your app can now process user queries and return answers instantly, providing an engaging and dynamic experience. This integration allows seamless interaction with the Gemini API, enhancing your Laravel app's functionality. Moving forward, you can expand on this by adding additional features, improving the user interface, or incorporating more advanced API capabilities.
For further details, refer to the Gemini API Client documentation.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
1

0 Comments

To engage in commentary, kindly proceed by logging in or registering