How to use Google Gemini AI Api in Laravel: A Step-by-Step Guide

Published on April 28, 2024. Last updated on January 22, 2025.
How to use Google Gemini AI Api in Laravel: A Step-by-Step Guide

In this guide, we'll walk you through the process of integrating and harnessing the capabilities of Google Gemini AI API in your Laravel application. Follow step-by-step instructions to seamlessly incorporate this cutting-edge technology into your projects, enabling you to leverage advanced AI features and enhance your application's functionality.

 

As the first step, install the gemini-api-php/laravel package to begin with the integration.

composer require gemini-api-php/laravel

 

Next, add your Gemini API Key to your .env file. If you dont have an API Key yet, you can create one in Google AI Studio. Gemini API offers a Free tier of 2 Requests per minute and 50 requests per day.

GEMINI_API_KEY="YOUR_API_KEY"

 

Here's an example of how you can use Gemini API in your Laravel application:

use GeminiAPI\Laravel\Facades\Gemini;

$geminiResponse = Gemini::generateText('PHP in less than 100 chars');
// PHP: A server-side scripting language used to create dynamic web applications.
// Easy to learn, widely used, and open-source.

 

If you want Gemini to explain an Images content. You can use the following method.

use GeminiAPI\Laravel\Facades\Gemini;

$explanation = Gemini::generateTextUsingImageFile(
    'image/jpeg',
    'elephpant.jpg',
    'Explain what is in the image'

);

// The image shows an elephant standing on the Earth.
// The elephant is made of metal and has a glowing symbol on its forehead.
// The Earth is surrounded by a network of glowing lines.
// The image is set against a starry background.

 

You can start a Chat conversation too.

use GeminiAPI\Laravel\Facades\Gemini;

$chat = Gemini::startChat();

print $chat->sendMessage('Hello World in PHP');
// echo "Hello World!";
// This code will print "Hello World!" to the standard output.

print $chat->sendMessage('in Go');
// fmt.Println("Hello World!")
// This code will print "Hello World!" to the standard output.

 

There are much more like Chat with History, Listing Models, etc.

Checkout GitHub Package to learn more.