Building AI-Native Apps With Laravel 13: The AI SDK, Vector Search, and Real Recommendations

  • Home
  • Laravel
  • Building AI-Native Apps With Laravel 13: The AI SDK, Vector Search, and Real Recommendations
Front
Back
Right
Left
Top
Bottom
FREAMEWORK

The Framework That Grew Up Alongside AI

When I started writing Laravel code, AI integrations meant bolting on a third-party package, fighting with API clients, and hoping that the OpenAI PHP SDK and your Laravel version were still friends. It worked, but it never felt native.

Laravel 13 changes that completely.

Laravel 13 introduces the first-party Laravel AI SDK, providing a unified API for text generation, tool-calling agents, embeddings, audio, images, and vector-store integrations.

That phrase — “unified API” — is the important part. One interface. Multiple AI providers. Your code doesn’t change when you switch from OpenAI to Anthropic. That’s the promise, and in my testing, it delivers.

AI-NATIVE

Building AI-Native Apps

The Laravel AI SDK: Getting Started

The Laravel AI SDK went stable on the same day as Laravel 13 — March 17, 2026. It’s not a third-party package. It’s part of the framework’s first-party ecosystem.

Installation
Copy to clipboard
composer require laravel/ai
php artisan ai:install
Configuration
Copy to clipboard
return [
    'default' => env('AI_PROVIDER', 'openai'),

    'providers' => [
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'model'   => 'gpt-4o',
        ],
        'anthropic' => [
            'api_key' => env('ANTHROPIC_API_KEY'),
            'model'   => 'claude-sonnet-4-20250514',
        ],
    ],
];
FIRST CALL
three lines

Your first AI call

Copy to clipboard
use Laravel\Ai\Facades\Ai;

$response = Ai::text('Summarize this customer review in one sentence: ' . $review);
echo $response; // Clean, concise summary

That’s it. No manual HTTP client. No API key juggling in controllers. Laravel handles the connection, error handling, and provider abstraction.

FAILOVER
Because APIs Go Down

Provider Failover

One of the most production-critical features of the Laravel AI SDK is automatic failover. When a provider runs out of credits or hits a quota limit, Laravel AI now automatically fails over to your next configured provider instead of throwing an exception.

Configure it like this:

Copy to clipboard
// config/ai.php
'fallback' => ['anthropic', 'openai'],

Your users never see an error. Your logs capture the fallback event. Your system stays alive. This is the kind of reliability feature that enterprise teams used to build themselves — now it’s baked in.

AI AGENT

Building an AI Agent

The real power comes with agents. Here’s how you define one:

Copy to clipboard
// app/Ai/Agents/ProductAdvisor.php
namespace App\Ai\Agents;

use Laravel\Ai\Agent;

class ProductAdvisor extends Agent
{
    protected string $system = <<<PROMPT
    You are a helpful product advisor for our e-commerce store.
    Only recommend products from our catalog. Be concise and friendly.
    PROMPT;
}
Then use it anywhere in your application:
Copy to clipboard
use App\Ai\Agents\ProductAdvisor;

$response = ProductAdvisor::make()->prompt(
    'I need a laptop for video editing under $2000'
);

return response()->json(['suggestion' => (string) $response]);
VECTOR
Building Intelligent Search With PostgreSQL + pgvector

Vector Search

This is where things get genuinely exciting for anyone building modern web apps.

Traditional search finds exact keyword matches. Vector search finds semantic meaning. A user searching for “comfortable running shoes” should also surface results tagged “athletic footwear for jogging” — even without shared keywords.

Laravel 13 deepens its semantic search story with native vector query support, embedding workflows, and related APIs. These features make it straightforward to build AI-powered search experiences using PostgreSQL + pgvector.

One line. No raw SQL. No pgvector syntax to memorize. Laravel abstracts the cosine similarity math entirely.
Step 1:
Set up pgvector in your migration
Copy to clipboard
Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->vector('embedding', 1536); // OpenAI ada-002 produces 1536-dim vectors
    $table->timestamps();
});
Step 2:
Generate and store embeddings
Copy to clipboard
use Laravel\Ai\Facades\Ai;
use App\Models\Article;

// When creating/updating articles:
$article = Article::create([
    'title' => $request->title,
    'body'  => $request->body,
]);

// Generate embedding from the article text
$embedding = Ai::embed($article->title . ' ' . $article->body);
$article->update(['embedding' => $embedding]);
Step 3:
Run semantic similarity searches
Copy to clipboard
// From Laravel 13 official docs — laravel.com/docs/13.x/releases
$articles = DB::table('articles')
    ->whereVectorSimilarTo('embedding', 'Best practices for web security')
    ->limit(10)
    ->get();

Laravel 13 introduces a new query builder method for this

EXAMPLE
AI-Powered Product Recommendations

Practical Example

Let’s put it all together. Here’s a real-world recommendation feature you could ship today:

The Plan
Controller
Copy to clipboard
namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Support\Facades\DB;

class RecommendationController extends Controller
{
    public function forProduct(Product $product): JsonResponse
    {
        // Find the 5 most semantically similar products
        $recommendations = DB::table('products')
            ->whereVectorSimilarTo('embedding', $product->description)
            ->where('id', '!=', $product->id)
            ->where('in_stock', true)
            ->limit(5)
            ->get(['id', 'name', 'price', 'image_url']);

        return response()->json([
            'product'         => $product->name,
            'recommendations' => $recommendations,
        ]);
    }
}
Route
Copy to clipboard
Route::get('/products/{product}/recommendations', RecommendationController::class);
Frontend fetch
Copy to clipboard
const res = await fetch(`/products/${productId}/recommendations`);
const { recommendations } = await res.json();
// Render your "You might also like" section

This is a production-grade recommendation system in under 20 lines of Laravel code. No separate ML infrastructure. No Python microservice. No vector database subscription. Just PostgreSQL + pgvector + Laravel 13.

For business leaders and investors
Traditional recommendation systems required a dedicated data science team, a separate ML pipeline, and significant infrastructure cost. Laravel 13’s AI SDK brings this capability to any team with a single Laravel developer. The ROI is immediate — better recommendations = higher average order value = more revenue.
FULL SDK
The Full SDK

Generating Audio and Images

The Laravel AI SDK goes well beyond text and embeddings:
Text-to-Speech (for accessibility features, podcasts, narration)
Copy to clipboard
use Laravel\Ai\Audio;

$audio = Audio::of('Welcome to our weekly product update!')->generate();
Storage::put('podcasts/latest.mp3', (string) $audio);
Image Generation
Copy to clipboard
use Laravel\Ai\Image;

$image = Image::of('A minimalist product photo on white background')->generate();
Storage::put('products/ai-generated/' . $product->id . '.jpg', (string) $image);

These aren’t experimental. They’re stable, first-party, and provider-agnostic. Switch from DALL·E to Stable Diffusion in your config without touching your application code.

MINDSET

The "AI-Native" Mindset Shift

There’s a bigger idea underneath all of this. Taylor Otwell and the Laravel team didn’t just add AI *features* to Laravel 13 — they made AI a first-class architectural concern.

The Laravel 13 changelog labels it “AI-native workflows.” That framing matters. It’s not “here’s a package to add AI.” It’s “AI is part of how you build with Laravel now.”

For developers, this is the most exciting signal the framework has sent in years. For businesses, it means your development team can build AI-powered features without needing a separate AI team. The barrier between “standard web app” and “AI-powered product” just dropped dramatically.

This quote lives on a sticky note above my monitor. Build simple systems that do smart things. That’s exactly what Laravel 13 enables.

Explore project snapshots or discuss custom web solutions.

Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better.

Edsger W. Dijkstra, On the Nature of Computing Science - 1984

Thank You for Spending Your Valuable Time

I truly appreciate you taking the time to read blog. Your valuable time means a lot to me, and I hope you found the content insightful and engaging!
Front
Back
Right
Left
Top
Bottom
FAQ's

Frequently Asked Questions

At stable release, the SDK supports OpenAI, Anthropic, Google Gemini, and OpenRouter. The provider-agnostic interface means more providers will be added without API changes. See laravel.com/docs/13.x/ai-sdk for the current provider list.

The SDK itself is free (it's part of Laravel). You'll pay for whatever AI provider you use (OpenAI, Anthropic, etc.). Embedding generation is typically the cheapest operation — often fractions of a cent per document. The failover feature helps control costs by routing to more economical providers when appropriate.

No — for most use cases. Laravel 13's vector search is built on PostgreSQL + pgvector, which is an open-source extension you can add to your existing database. For truly massive scale (millions of vectors), dedicated vector databases may still make sense, but pgvector handles most web app workloads efficiently.

Yes — it's one of the most accessible entry points into AI development. If you know basic Laravel, you can build your first AI feature in under 30 minutes. The official docs at laravel.com/docs/13.x/ai-sdk are clear and example-rich.

Absolutely. Features like provider failover, full testability, and consistent APIs make it production-ready for commercial SaaS. The agent pattern is particularly powerful for building specialized assistants scoped to your business domain.

Comments are closed