Skip to content
Laravel 13 Deep Dive: AI SDK, Vector Search & Framework-First AI Workflows

Laravel 13 Deep Dive: AI SDK, Vector Search & Framework-First AI Workflows

Laravel 13 ships a provider-agnostic AI SDK with agents, tool calling, and multimodal support, adds native pgvector-powered semantic search, JSON:API resources, PHP attributes for declarative configuration, CSRF hardening, centralized queue routing, and atomic cache renewal — all with a near-zero-breaking-change upgrade path from Laravel 12.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community

Laravel 13 was released on March 17, 2026 at Laracon EU. The framework positions itself around three pillars: AI-native workflows, stronger defaults, and more expressive APIs. It requires PHP ≥ 8.3 (supports 8.3–8.5) and promises virtually zero breaking changes for most applications. Bug fixes end Q3 2027; security fixes end March 17, 2028. Laravel 12 bug fixes ended August 13, 2026, leaving only security patches until February 2027, so the upgrade window is narrowing.

I. Laravel AI SDK: First-Party, Provider-Agnostic

This is the first time Laravel bundles AI capabilities as a first-party SDK. The core design is provider-agnostic: business code programs against Laravel abstractions, and switching between OpenAI, Anthropic, Gemini, or local models only requires a configuration change.

1.1 Defining an Agent

Agents extend Laravel\Ai\Agents\Agent. They declare system instructions and register tools the model may invoke autonomously.

<?php
namespace App\Ai\Agents;
use Laravel\Ai\Agents\Agent;
use App\Ai\Tools\OrderLookupTool;

class SalesCoach extends Agent {
    // System instructions: define role and boundaries
    protected string $instructions = <<<PROMPT
    You are a sales coach. Based on call transcripts, identify script issues and give improvement suggestions.
    Only analyze sales-related content, respond in Chinese.
    PROMPT;
    // Register tools: model can call autonomously
    protected array $tools = [OrderLookupTool::class];
}

Calling code is minimal:

<?php
use App\Ai\Agents\SalesCoach;

$response = SalesCoach::make()
    ->prompt('Analyze this sales conversation: ' . $transcript);
return (string) $response;
make()

static factory + prompt() single-shot execution returns an object that can be cast to string while retaining the raw response (token usage, tool call traces) for auditing.

1.2 Tool Calling

Tools let the model "act" rather than just "speak". A tool extends Laravel\Ai\Tools\Tool, declares a description, and implements a handle method.

<?php
namespace App\Ai\Tools;
use Laravel\Ai\Tools\Tool;
use App\Models\Order;

class OrderLookupTool extends Tool {
    protected string $description = 'Look up order status by order number';
    public function handle(string $orderNo): string {
        $order = Order::where('order_no', $orderNo)->first();
        return $order
            ? "Order {$order->order_no} current status: {$order->status}"
            : 'Order not found';
    }
}

1.3 Multimodal: Image, Audio, Vectors in One Line

<?php
use Laravel\Ai\Image;
use Laravel\Ai\Audio;
use Illuminate\Support\Str;

// Text-to-image
$image = Image::of('A ginger cat sitting on a mechanical keyboard')->generate();
Storage::disk('s3')->put('cat.png', (string) $image);

// Speech synthesis (assistant, narration, accessibility)
$audio = Audio::of('Payment successful, thank you for your purchase.')->generate();

// String directly to embeddings (fuel for semantic search)
$embeddings = Str::of('Napa Valley has great wine.')->toEmbeddings();

Architectural value: previously integrating AI meant stacking SDK clients in controllers, hand-writing retries and timeouts, and scattering prompts. Now they are framework-level services — with unified configuration, logging, testing, and mocking — just like databases and queues.

II. Semantic / Vector Search: Framework-Level RAG Foundation

Laravel 13 completes the last piece at the database layer. Using PostgreSQL + pgvector, the full flow is:

2.1 Table & Vector Column

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

return new class extends Migration {
    public function up(): void {
        DB::statement('CREATE EXTENSION IF NOT EXISTS vector');
        Schema::create('documents', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            // 1536 dimensions — adjust per model used
            $table->vector('embedding', 1536)->nullable();
            $table->timestamps();
        });
        // Vector index: HNSW, key for approximate nearest neighbor search
        DB::statement(
            'CREATE INDEX documents_embedding_idx ON documents USING hnsw (embedding vector_cosine_ops)'
        );
    }
};

2.2 Generate Embedding on Write (Model Event Auto-Completes)

<?php
use Illuminate\Database\Eloquent\Model;

class Document extends Model {
    protected static function booted(): void {
        static::saving(function (Document $doc) {
            if ($doc->isDirty('body')) {
                $doc->embedding = (string) Str::of($doc->body)->toEmbeddings();
            }
        });
    }
}

2.3 Similarity Retrieval

<?php
$documents = DB::table('documents')
    ->whereVectorSimilarTo('embedding', 'Best wineries in Napa Valley')
    ->limit(10)
    ->get();

Two important notes: whereVectorSimilarTo accepts a natural language string ; the framework handles vectorization and distance calculation internally — no manual embedding conversion required.

MySQL / SQLite are not supported; PostgreSQL + pgvector is required. Existing MySQL projects must evaluate this infrastructure cost before upgrading.

III. JSON:API Resources: Spec-Compliant APIs Out of the Box

Teams building mobile backends or third-party platforms no longer need third-party packages. Laravel 13 includes JSON:API resources that automatically handle resource serialization, relationship inclusion ( ?include=author), sparse fieldsets ( ?fields[articles]=title,body), pagination links, and compliant response headers.

<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonApiResource; // indicative: use official docs class name

class ArticleResource extends JsonApiResource {
    public function toArray($request): array {
        return [
            'type'       => 'articles',
            'id'         => (string) $this->id,
            'attributes' => [
                'title' => $this->title,
                'body'  => $this->body,
            ],
        ];
    }
    // Declare includable relationships
    public function includePaths(): array {
        return ['author', 'comments'];
    }
}

Clients request GET /api/articles/1?include=author,comments and receive a spec-compliant compound document with cache-friendly meta information.

IV. PHP Attributes Everywhere: Configuration Returns to Code

Laravel 13 adds native attribute support at 15+ framework entry points. High-frequency examples: #[Middleware('auth')] — Controller / method-level middleware #[Authorize('create', Post::class)] — Method-level authorization check #[Tries(5)] / #[Backoff([10, 30, 60])] — Job retry & backoff strategy #[Timeout(120)] / #[FailOnTimeout] — Job timeout behavior

Eloquent/Event/Notification/Validation etc. — Declarative configuration

Controller before/after:

// Before: in constructor $this->middleware(...), or route file with policy
// Now:
use Illuminate\Routing\Attributes\Controllers\Authorize;
use Illuminate\Routing\Attributes\Controllers\Middleware;

#[Middleware('auth')]
class CommentController {
    #[Middleware('subscribed')]
    #[Authorize('create', [Comment::class, 'post'])]
    public function store(Post $post) {
        // Authorization failure auto-throws 403, middleware runs in declared order
    }
}

Jobs similarly:

use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\Timeout;

#[Tries(5)]
#[Timeout(120)]
class ProcessPodcast implements ShouldQueue {
    // handle() focuses on business, scheduling params no longer scattered across dispatch sites
}

V. Security Hardening: PreventRequestForgery

The CSRF middleware is renamed from VerifyCsrfToken to PreventRequestForgery and upgraded with origin-aware validation : using the Sec-Fetch-Site header on modern browsers, suspicious cross-origin requests are intercepted before token validation. The token mechanism remains compatible.

Upgrade focus: if you customized CSRF logic (overrode handle(), allowlisted URIs, integrated special gateways), review app/Http/Middleware. The old class name works as a deprecated alias but renaming is recommended.

VI. Queue::route(): Centralized Queue Routing

<?php
// AppServiceProvider::boot()
use Illuminate\Support\Facades\Queue;

Queue::route(ProcessPodcast::class, connection: 'redis', queue: 'podcasts');
Queue::route(GenerateReport::class, connection: 'sqs', queue: 'reports');

Jobs no longer declare public $connection = 'redis'. Operations can adjust queue allocation in one place.

VII. Cache::touch(): Renewal Without Retrieval

// Before: three steps, serializes value even when large
$value = Cache::get('hot-key');
Cache::forget('hot-key');
Cache::put('hot-key', $value, 600);

// Now: atomic renewal at storage layer, saves network & serialization overhead
Cache::touch('hot-key', 600);

Highly practical for hot keys (homepage aggregates, config snapshots, rate-limit counters).

VIII. Upgrade Checklist

Step 0 | Environment: Server / CI / Docker images unified to PHP 8.3+ — hard requirement.

Step 1 | Dependencies:

"require": {
    "php": "^8.3",
    "laravel/framework": "^13.0"
},
"require-dev": {
    "laravel/tinker": "^3.0",
    "phpunit/phpunit": "^12.0"
}

Step 2 | Regression Test Focus:

composer update
php artisan test

Custom CSRF middleware / allowlists

Cache value serialization format changes (first miss after upgrade is normal, watch for stampede) DB::delete() and similar queries returning affected rows — edge behavior from old defaults

Queue workers rolling restart to avoid old processes handling new payloads

Step 3 | Automation Channels (pick one):

Laravel Boost (first-party MCP server): run /upgrade-laravel-v13 in Claude Code / Cursor — AI walks the upgrade guide, rewrites code, runs tests.

Laravel Shift : upload repo, get a full upgrade diff PR, review and merge.

References: Laravel official Release Notes & Upgrade Guide (laravel.com/docs). Gist collection of all code snippets from this article.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Vector SearchCSRFAI SDKpgvectorUpgrade GuideJSON:APICache TouchLaravel 13PHP AttributesQueue Routing
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.