Ollama with Laravel
Using Ollama with Laravel needs no special package: Laravel's built-in HTTP client can call the Ollama REST API directly. This keeps dependencies minimal and gives you full control.
Configure the Host
// .env
OLLAMA_HOST=http://127.0.0.1:11434
OLLAMA_MODEL=llama3.2
// config/services.php
'ollama' => [
'host' => env('OLLAMA_HOST', 'http://127.0.0.1:11434'),
'model' => env('OLLAMA_MODEL', 'llama3.2'),
],(configuration only)
A Chat Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class AskController extends Controller
{
public function __invoke(Request $request)
{
$data = $request->validate(['question' => 'required|string|max:2000']);
$response = Http::timeout(120)
->post(config('services.ollama.host') . '/api/chat', [
'model' => config('services.ollama.model'),
'stream' => false,
'messages' => [
['role' => 'system', 'content' => 'Answer briefly and politely.'],
['role' => 'user', 'content' => $data['question']],
],
])
->throw();
return ['answer' => $response->json('message.content')];
}
}POST /ask {"question":"What is Laravel?"}
{"answer":"Laravel is a PHP web framework with elegant syntax for building modern web applications."}
(Sample response.)Http::timeout(120) matters: the first request may wait while the model loads into memory. ->throw() turns HTTP errors into exceptions that Laravel reports normally.
Structured Data from Text
$response = Http::post(config('services.ollama.host') . '/api/generate', [
'model' => 'llama3.2',
'prompt' => "Extract product and quantity: 'I need 3 blue mugs'",
'stream' => false,
'format' => [
'type' => 'object',
'properties' => ['product' => ['type' => 'string'], 'quantity' => ['type' => 'integer']],
'required' => ['product', 'quantity'],
],
]);
$order = json_decode($response->json('response'), true);['product' => 'blue mugs', 'quantity' => 3] (Sample response.)
Tips for Laravel Apps
- Run slow generations in queued jobs and notify the user when done.
- Cache answers to repeated questions.
- Packages such as Prism PHP offer a provider-agnostic API if you later switch between Ollama and cloud models.
Frequently asked questions
Is there an official Ollama PHP library?
Not from the Ollama team at the time of writing; community packages exist, but the Laravel HTTP client is enough for most needs.
Why does my Laravel request time out?
The default timeout is 30 seconds. Model loading plus generation can take longer, so raise it with Http::timeout().
Can I stream Ollama responses in Laravel?
Yes, by using a streamed response and reading the HTTP body incrementally, but a simpler start is non-streaming plus queued jobs.