Laravel Daily's

Supercharging the Ultimate PHP Web Framework with Native AI Integrations

hero image

AI features are becoming part of everyday web applications. Users expect search assistants, document analysis, recommendations, automation, and natural-language interfaces.

Laravel gives PHP developers a direct path to those features. The Laravel AI SDK connects your application to providers such as OpenAI and Anthropic through one expressive API. It also supports agents, tools, structured output, streaming, queues, embeddings, vector stores, and testing.

Laravel Boost improves the development process itself. It gives AI coding agents the context they need to understand your Laravel application.

Together, these tools extend Laravel from a productive PHP web framework into a practical foundation for AI-native products.

The Laravel AI stack: One framework, two AI workflows

Laravel AI development has two distinct sides.

The first side runs inside your application. The AI SDK lets you call models, build agents, define tools, store conversations, and search your data.

The second side supports development. Boost connects AI coding agents to your routes, database schema, logs, Artisan commands, and version-specific documentation.

This separation matters. Your application can use AI to serve customers, while Boost helps your team build and maintain the application.

The AI SDK is installed as a normal Composer package:

composer require laravel/ai

php artisan vendor:publish \
    --provider="Laravel\Ai\AiServiceProvider"

php artisan migrate

The published migrations create the tables needed for conversation storage. Add provider credentials to .env:

OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key

Keep these values on the server. Never expose provider keys in a browser bundle or public API response.

Laravel AI SDK architecture with agents, tools, providers, PHP, and APIs

OpenAI integration: Build a Laravel agent

Agents are the main building block in the Laravel AI SDK. Each agent is a PHP class that defines instructions, conversation context, tools, and optional structured output.

Create an agent with Artisan:

php artisan make:agent SupportAssistant

A simple agent can look like this:

<?php

namespace App\Ai\Agents;

use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;

class SupportAssistant implements Agent
{
    use Promptable;

    public function instructions(): string
    {
        return 'You are a concise support assistant.
            Answer only from the application knowledge base.';
    }
}

You can call the agent from a controller, service, command, or queued job:

use App\Ai\Agents\SupportAssistant;

$response = (new SupportAssistant)->prompt(
    'How do I reset my password?'
);

return (string) $response;

The SDK uses the default provider and model configured in config/ai.php. You can also select a provider for an individual request.

use App\Ai\Agents\SupportAssistant;
use Laravel\Ai\Enums\Lab;

$response = (new SupportAssistant)->prompt(
    'Summarize this support request.',
    provider: Lab::OpenAI,
);

return (string) $response;

This keeps your application code independent from provider-specific request formats. Switching from OpenAI to Anthropic does not require rewriting HTTP clients, request payloads, or response parsers.

For a practical REST API with PHP, expose the agent through a Laravel route:

use App\Ai\Agents\SupportAssistant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Ai\Enums\Lab;

Route::post('/api/ask', function (Request $request) {
    $validated = $request->validate([
        'question' => ['required', 'string', 'max:2000'],
    ]);

    $response = (new SupportAssistant)->prompt(
        $validated['question'],
        provider: Lab::OpenAI,
    );

    return response()->json([
        'answer' => (string) $response,
    ]);
});

Laravel handles validation, routing, middleware, authentication, and JSON responses. The AI integration remains a small part of a familiar PHP application structure.

Anthropic integration: Change providers without changing architecture

Anthropic uses the same agent interface. You can select it per request:

use App\Ai\Agents\SupportAssistant;
use Laravel\Ai\Enums\Lab;

$response = (new SupportAssistant)->prompt(
    'Review this customer message and suggest a reply.',
    provider: Lab::Anthropic,
);

return (string) $response;

You can also configure a specific provider in config/ai.php:

'providers' => [
    'openai' => [
        'driver' => 'openai',
        'key' => env('OPENAI_API_KEY'),
    ],

    'anthropic' => [
        'driver' => 'anthropic',
        'key' => env('ANTHROPIC_API_KEY'),
    ],
],

Provider selection can be useful when different tasks need different models. You might use one provider for fast classification and another for long-form analysis.

The SDK also supports failover:

$response = (new SupportAssistant)->prompt(
    'Summarize this document.',
    provider: [Lab::OpenAI, Lab::Anthropic],
);

If the primary provider encounters a supported outage, rate limit, or availability failure, the SDK can try the next provider.

Structured output: Make AI responses predictable

Free-form text works for chat. Most business workflows need a defined response shape.

Implement HasStructuredOutput and define a schema:

<?php

namespace App\Ai\Agents;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;

class LeadClassifier implements Agent, HasStructuredOutput
{
    use Promptable;

    public function instructions(): string
    {
        return 'Classify incoming leads using the requested schema.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'qualified' => $schema->boolean()->required(),
            'priority' => $schema
                ->string()
                ->enum(['low', 'medium', 'high'])
                ->required(),
            'reason' => $schema->string()->required(),
        ];
    }
}

The response can then be accessed like an array:

$response = (new LeadClassifier)->prompt(
    'A Series B startup needs enterprise Laravel support.'
);

if ($response['qualified']) {
    // Route the lead to your sales workflow.
}

This pattern fits naturally with Laravel validation, jobs, notifications, events, and Eloquent models.

Vector search: Give agents access to your knowledge

An AI model does not automatically know your private documentation or customer data. Retrieval-augmented generation, or RAG, solves this by retrieving relevant content before generating an answer.

The Laravel AI SDK supports embeddings and similarity search. Native vector queries currently require PostgreSQL with the pgvector extension.

Define an embedding column in a migration:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::ensureVectorExtensionExists();

Schema::create('documents', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->vector('embedding', dimensions: 1536)->index();
    $table->timestamps();
});

Cast the column on the model:

protected function casts(): array
{
    return [
        'embedding' => 'array',
    ];
}

Generate an embedding when a document is created:

use Laravel\Ai\Embeddings;
use Laravel\Ai\Enums\Lab;

$response = Embeddings::for([$document->content])
    ->generate(
        provider: Lab::OpenAI,
        model: 'text-embedding-3-small',
    );

$document->update([
    'embedding' => $response->embeddings[0],
]);

You can query similar records directly through Eloquent:

$documents = Document::query()
    ->whereVectorSimilarTo(
        'embedding',
        'How do I configure queue workers?',
        minSimilarity: 0.4,
    )
    ->limit(10)
    ->get();

The query can receive an embedding array or plain text. Laravel generates the embedding when you provide a string.

Bright illustration of Laravel vector search, PostgreSQL, pgvector, documents, and an AI agent

SimilaritySearch: Turn retrieval into an agent tool

The SDK includes a SimilaritySearch tool for agents:

use App\Models\Document;
use Laravel\Ai\Tools\SimilaritySearch;

public function tools(): iterable
{
    return [
        SimilaritySearch::usingModel(
            model: Document::class,
            column: 'embedding',
            minSimilarity: 0.7,
            limit: 10,
            query: fn ($query) => $query->where('published', true),
        ),
    ];
}

The agent can now search your knowledge base when answering a question. You can scope the query by tenant, account, user, or publication status.

For sensitive data, pass authorization context through your application code. Do not let the model decide which user’s records it can access. Use authenticated scopes, allowlists, selected columns, and read-only database connections.

Enable embedding caching when the same content is processed repeatedly:

'caching' => [
    'embeddings' => [
        'cache' => true,
        'store' => env('CACHE_STORE', 'database'),
    ],
],

Caching reduces duplicate provider calls and keeps indexing costs predictable.

Laravel Boost: Improve AI-assisted development

The Boost documentation covers a separate but complementary use case.

Install Boost as a development dependency:

composer require laravel/boost --dev
php artisan boost:install

Boost exposes your application through Model Context Protocol tools. AI coding agents can inspect:

  • PHP and Laravel versions
  • Installed Composer packages
  • Routes and middleware
  • Database schema
  • Application configuration
  • Logs and browser errors
  • Artisan commands
  • Laravel documentation

Boost also provides version-aware AI guidelines. This helps coding agents produce code that matches your installed Laravel, Livewire, Inertia, Tailwind, Pest, and PHPUnit versions.

Bright illustration of Laravel Boost with an AI developer, MCP connector, routes, database schema, logs, and documentation

That context reduces a common problem with AI-generated code: technically valid suggestions that do not match your application or framework version.

Ship AI features with Laravel’s existing tools

The Laravel AI SDK fits the rest of the ecosystem.

Use queues for long-running analysis. Stream responses through server-sent events. Broadcast progress with Reverb and Echo. Store generated files through Laravel’s filesystem. Monitor application behavior with Nightwatch. Deploy through Laravel Cloud, Forge, or another existing Laravel workflow.

The SDK also includes fakes and assertions for agents, embeddings, images, audio, files, and vector stores. That makes AI features testable without calling a paid provider in every test.

The practical path is straightforward:

  1. Install laravel/ai.
  2. Configure OpenAI or Anthropic credentials.
  3. Create one focused agent.
  4. Expose it through a protected Laravel route or job.
  5. Add structured output where your application needs predictable data.
  6. Add embeddings and SimilaritySearch for private knowledge.
  7. Install Boost to improve your development workflow.
  8. Add authorization, logging, rate limits, and tests before production.

Laravel already provides the application foundation. The AI SDK supplies the model layer, while Boost supplies the development context. Together, they let PHP developers build AI-powered products without splitting the application into unrelated languages or services.

Previous
Graceful Data Loading in Inertia 3.x: Rescue Slots & Deferred Props in Laravel + Vue SPAs
Next
Inertia 3.x's Built-in HTTP Client: Replacing Axios in Your Laravel + Vue SPAs