This content originally appeared on DEV Community and was authored by Hossein Hezami
Tired of reading docs and just want to see the code? Let’s dive straight into how you can use the hosseinhezami/laravel-gemini
package to add powerful AI features to your Laravel application. The API is clean, fluent, and incredibly powerful.
Installation & Setup
First, get the package.
composer require hosseinhezami/laravel-gemini
Publish the config file and set your API key.
php artisan vendor:publish --tag=gemini-config
# .env
GEMINI_API_KEY=your_gemini_api_key_here
Code Examples: See It in Action
1. Basic Text Generation & Chat
The TextBuilder
makes generating text or creating a chat interface simple.
use HosseinHezami\LaravelGemini\Facades\Gemini;
// Simple prompt
$response = Gemini::text()
->prompt('Write a tagline for a developer blog.')
->generate();
echo $response->content();
// Chat with history
$history = [
['role' => 'user', 'parts' => [['text' => 'Hello!']]],
['role' => 'model', 'parts' => [['text' => 'Hi there! How can I help?']]]
];
$response = Gemini::text()
->prompt('What’s the weather like?')
->history($history)
->temperature(0.7)
->generate();
echo $response->content();
2. Structured Data Extraction
Need consistent JSON output from a messy prompt? Use structuredSchema
.
$response = Gemini::text()
->structuredSchema([
'type' => 'object',
'properties' => [
'sentiment' => [
'type' => 'string',
'enum' => ['positive', 'negative', 'neutral']
],
'confidence' => ['type' => 'number'],
'key_points' => {
'type' => 'array',
'items' => {'type' => 'string'}
}
],
'required' => ['sentiment']
])
->prompt('The product is amazing but the delivery was late. I love the features though.')
->generate();
$analysis = json_decode($response->content());
// $analysis->sentiment, $analysis->key_points, etc.
3. Image Generation
Generate images from a text description.
$response = Gemini::image()
->prompt('A minimalist logo for a tech startup called "Nexus", using blue and green')
->generate();
// Save the generated image directly
$response->save(storage_path('app/logo.png'));
4. Document Understanding
Upload a file (PDF, DOC, image) and ask questions about it.
// First, upload the file to Gemini's servers
$fileUri = Gemini::files()->upload('document', $pathToInvoicePdf);
// Then, use it in a prompt
$response = Gemini::text()
->upload('document', $pathToInvoicePdf) // or use the $fileUri
->prompt('What is the total amount due on this invoice?')
->generate();
echo $response->content();
5. Text-to-Speech (Audio)
Generate spoken audio from text.
$response = Gemini::audio()
->prompt('Welcome to our application. We are thrilled to have you on board.')
->voiceName('Kore') // Check docs for available voices
->generate();
// The package smartly handles the binary response,
// allowing you to save it directly.
$response->save(public_path('audio/welcome.mp3'));
6. Real-Time Streaming
Crucial for building chat interfaces that feel fast and responsive.
// In your controller (e.g., app/Http/Controllers/ChatController.php)
public function stream(Request $request)
{
return response()->stream(function () use ($request) {
Gemini::text()
->model('gemini-2.5-flash-lite') // Use a fast model for streaming
->prompt($request->query('message'))
->stream(function ($chunk) {
$text = $chunk['text'] ?? '';
if (connection_aborted()) return;
echo "data: " . json_encode(['text' => $text]) . "\n\n";
ob_flush();
flush();
});
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
'X-Accel-Buffering' => 'no',
]);
}
Ready to Build?
This is just the surface. The package also handles video generation, embeddings, and full file management.
For complete documentation, check out the official docs:
https://hosseinhezami.github.io/laravel-gemini/
Source:
- https://github.com/hosseinhezami/laravel-gemini
- https://packagist.org/packages/hosseinhezami/laravel-gemini
What will you build first? Let me know in the comments!
This content originally appeared on DEV Community and was authored by Hossein Hezami