This content originally appeared on DEV Community and was authored by Martin Tonev
Artificial Intelligence (AI) is no longer a buzzword. It’s a core part of modern web applications. From personalized recommendations to intelligent automation, AI can dramatically improve the functionality and user experience of Laravel projects.
In this article, we’ll walk through real, production-level AI integrations in Laravel projects. We’ll skip the hype and get into how you can actually use AI, including services like OpenAI, computer vision, and ML models, inside your Laravel stack.
Common AI Use Cases in Laravel Projects
Before diving into the code, here are some real-world features powered by AI that Laravel apps can implement:
- Text generation (emails, summaries, product descriptions) using OpenAI or Claude
- Chatbots and conversational interfaces with context-aware memory
- Image classification and analysis (e.g., product tagging, face detection)
- Voice-to-text or audio transcription using Whisper or AssemblyAI
- Recommendation engines for content, products, or actions
- Predictive analytics using historical data (ML models)
- Spam and abuse detection using NLP models
Laravel AI Integration Workflow
Let’s walk through the structure of a Laravel app that integrates with AI in a scalable and testable way.
1. Set Up Your Laravel App
Make sure you’re on Laravel 10+ or 11+ with PHP 8.2+ to ensure compatibility with modern packages.
laravel new ai-demo-app
cd ai-demo-app
Install HTTP client (usually already installed via Laravel):
composer require guzzlehttp/guzzle
Or use Laravel’s built-in HTTP client (Http::post()
from Illuminate\Support\Facades\Http
).
2. Using OpenAI GPT in Laravel
Let’s build an endpoint that uses OpenAI’s API to generate a summary for a given blog post.
Step 1: Create an AI Service
php artisan make:service OpenAIService
Create app/Services/OpenAIService.php
:
namespace App\Services;
use Illuminate\Support\Facades\Http;
class OpenAIService
{
public function summarizeText(string $text): string
{
$response = Http::withToken(config('services.openai.key'))
->post('https://api.openai.com/v1/chat/completions', [
'model' => 'gpt-4',
'messages' => [
['role' => 'system', 'content' => 'You are an assistant that summarizes text.'],
['role' => 'user', 'content' => "Summarize this:\n$text"],
],
'temperature' => 0.7,
]);
return $response['choices'][0]['message']['content'] ?? 'No summary available.';
}
}
Step 2: Add OpenAI API Key
In .env
:
OPENAI_API_KEY=your_api_key_here
In config/services.php
:
'openai' => [
'key' => env('OPENAI_API_KEY'),
],
Step 3: Create a Controller
php artisan make:controller AIController
In AIController.php
:
use App\Services\OpenAIService;
public function summarize(Request $request, OpenAIService $openAI)
{
$request->validate([
'text' => 'required|string|min:10',
]);
$summary = $openAI->summarizeText($request->text);
return response()->json(['summary' => $summary]);
}
Define a route:
Route::post('/ai/summarize', [AIController::class, 'summarize']);
Using AI for Image Classification
You can also connect your Laravel backend to image classification models like:
- YOLOv5/YOLOv8 (via Python)
- Replicate.com API
- Google Vision or AWS Rekognition
Here’s a simplified example using Replicate.
Step 1: Upload Image and Call Replicate API
Create a new controller or use the existing AIController:
public function classifyImage(Request $request)
{
$request->validate([
'image' => 'required|image|max:2048',
]);
$path = $request->file('image')->store('temp', 'public');
$imageUrl = asset('storage/' . $path);
$response = Http::withToken(config('services.replicate.key'))
->post('https://api.replicate.com/v1/predictions', [
'version' => 'your-model-version-id', // from replicate dashboard
'input' => ['image' => $imageUrl],
]);
return response()->json($response->json());
}
Add file upload handling and cleanup as needed.
Integrating AI-Powered Chatbot
For apps that need a conversational chatbot (support, education, SaaS onboarding), you can stream responses from OpenAI’s API.
Stream ChatGPT Responses in Laravel
public function chat(Request $request)
{
$response = Http::withToken(config('services.openai.key'))
->withHeaders([
'Accept' => 'text/event-stream',
])
->post('https://api.openai.com/v1/chat/completions', [
'model' => 'gpt-4',
'messages' => $request->messages,
'stream' => true,
]);
return response()->stream(function () use ($response) {
echo $response->body();
flush();
}, 200, ['Content-Type' => 'text/event-stream']);
}
You can stream the response in Livewire or Vue to simulate a “typing” chatbot.
Advanced: Running AI Locally (e.g., Python + Laravel)
In some projects (such as image detection, segmentation, or audio processing), you’ll need to offload AI work to Python.
Approach:
- Laravel triggers a Python script (e.g., via
symfony/process
or API). - Python model does the heavy lifting (e.g., YOLOv8).
- Laravel receives results via JSON or file output.
Example:
$process = new Process(['python3', base_path('ai/detect.py'), $imagePath]);
$process->run();
$result = json_decode($process->getOutput(), true);
Or, run Python AI models via a local Flask API and make HTTP calls from Laravel.
Testing AI Integrations
Always mock third-party API responses in your tests:
Http::fake([
'api.openai.com/*' => Http::response([
'choices' => [
['message' => ['content' => 'Test summary']]
]
], 200),
]);
Then use Laravel’s test methods as usual:
$this->postJson('/api/ai/summarize', ['text' => 'Test content'])
->assertJson(['summary' => 'Test summary']);
Packages Worth Exploring
- laravel-openai – Official OpenAI PHP SDK for Laravel
- laravel-zero – Useful for CLI-based AI tools
- Livewire or Inertia – Build reactive frontend chatbots
- Spatie Laravel Image – Useful for processing uploaded images
Conclusion
AI can give your Laravel app superpowers. But the key is not just integration, it’s orchestration.
Start small. Build one useful feature like auto-summarization, AI chatbot, or intelligent image labeling. Then expand to deeper automation, decision-making, or predictive models.
With Laravel’s clean architecture and AI’s growing ecosystem, this is the perfect time to merge them.
Let me know if you want this article turned into a Markdown, DOCX, or blog-ready HTML version.
This content originally appeared on DEV Community and was authored by Martin Tonev