Laravel 13: Building an AI-Powered Application with Laravel's New Features
Backend • 5 min read

Laravel 13: Building an AI-Powered Application with Laravel's New Features

Julius Fasema

Author

Explore Laravel 13 with practical examples covering the Laravel AI SDK, agents, embeddings, vector search, JSON:API resources, PHP attributes, queue routing and security changes.

Introduction

Laravel continues its annual major-release cycle with Laravel 13, released on March 17, 2026. The release requires PHP 8.3 or later and focuses heavily on AI-native application development while continuing to improve Laravel's existing APIs, security, queues, caching and database capabilities.

For developers who have worked with Laravel 10, 11 or 12, Laravel 13 is particularly interesting because many of the changes are additive rather than disruptive. Laravel describes the release as having relatively minimal breaking changes while introducing several substantial capabilities.

Among the most notable additions are:

  • First-party Laravel AI SDK
  • AI agents and tool calling
  • Text generation
  • Image generation
  • Audio generation and transcription
  • Embeddings
  • Semantic and vector search
  • JSON:API resources
  • Expanded PHP attribute support
  • Class-based queue routing
  • Improved request-forgery protection
  • Cache::touch()
  • Continued improvements to Eloquent and database integrations

This article takes a practical look at these features rather than simply reproducing the Laravel release notes.

1. What You Need Before Using Laravel 13

Laravel 13 requires PHP 8.3–8.5 according to the current support table. Laravel 13 was released on March 17, 2026, with bug fixes scheduled through Q3 2027 and security fixes through March 17, 2028.

You can verify your PHP version with:

php -v

You should see PHP 8.3 or newer.

For example:

PHP 8.3.x

You can also check your Composer installation:

composer --version

2. Creating a Laravel 13 Application

If you already have the Laravel installer installed, create a new application with:

laravel new laravel13-demo

Alternatively, Composer can be used to create the application:

composer create-project laravel/laravel laravel13-demo

Move into the project:

cd laravel13-demo

Start the development server:

php artisan serve

Laravel will normally make the application available at:

http://127.0.0.1:8000

Open that address in your browser.

3. Laravel 13 and PHP 8.3

The PHP 8.3 requirement is important when upgrading existing applications.

Check your application's Laravel version:

php artisan --version

For example:

Laravel Framework 13.x

You should also inspect composer.json:

{

    "require": {

        "php": "^8.3",

        "laravel/framework": "^13.0"

    }

}

The ^13.0 constraint allows compatible Laravel 13 minor and patch releases while preventing Composer from automatically moving the application to Laravel 14.

Laravel's documentation recommends version constraints such as ^13.0 when referencing Laravel because major releases can contain breaking changes.

4. Installing the Laravel AI SDK

One of the biggest additions in Laravel 13 is the first-party Laravel AI SDK.

Instead of every Laravel developer implementing separate integrations for AI providers, the SDK provides a Laravel-oriented interface for working with AI models.

Install it with Composer:

composer require laravel/ai

Then publish its configuration and migrations:

php artisan vendor:publish \

    --provider="Laravel\Ai\AiServiceProvider"

Run the migrations:

php artisan migrate

The SDK supports providers including OpenAI, Anthropic, Gemini, Groq, Mistral, DeepSeek, xAI and others, with configuration available through environment variables and config/ai.php.

For example:

OPENAI_API_KEY=your-api-key

The exact provider and model configuration should be selected according to the AI service you intend to use.

5. Building a Simple AI Agent

Let's build something practical.

Imagine we are developing an application for developers where users can submit a piece of code and ask an AI assistant to explain it.

Create an agent:

php artisan make:agent CodeExplainer

This gives us an application-specific place to define the AI agent's behavior.

A simplified agent might look like:

<?php

namespace App\Ai\Agents;

use Laravel\Ai\Contracts\Agent;

use Laravel\Ai\Promptable;

class CodeExplainer implements Agent

{

    use Promptable;

    public function instructions(): string

    {

        return <<<'PROMPT'

            You are an experienced software engineer.

            Explain programming code clearly to developers.

            Identify what the code does, important concepts,

            possible problems, and practical improvements.

            Prefer concise explanations with examples.

        PROMPT;

    }

}

We can then prompt the agent from our application:

use App\Ai\Agents\CodeExplainer;

$response = (new CodeExplainer)->prompt(

    'Explain this PHP function: function add($a, $b) { return $a + $b; }'

);

return (string) $response;

The important idea is that the AI behavior becomes part of an ordinary Laravel application rather than a completely separate AI service.

Laravel's AI SDK provides a consistent interface for agents, structured output, tools, conversations, embeddings, images, audio and other AI functionality.

6. Building a Simple Laravel AI Controller

For a more realistic application, let's expose the AI functionality through an HTTP endpoint.

Create a controller:

php artisan make:controller CodeExplainerController

Then:

<?php

namespace App\Http\Controllers;

use App\Ai\Agents\CodeExplainer;

use Illuminate\Http\Request;

class CodeExplainerController extends Controller

{

    public function explain(Request $request)

    {

        $request->validate([

            'code' => ['required', 'string'],

        ]);

        $response = (new CodeExplainer)->prompt(

            'Explain this code:

            ' . $request->input('code')

        );

        return response()->json([

            'explanation' => (string) $response,

        ]);

    }

}

Add a route:

use App\Http\Controllers\CodeExplainerController;

 

Route::post('/api/explain-code', [

    CodeExplainerController::class,

    'explain'

]);

Now a frontend or API client can send:

{

    "code": "function add($a, $b) { return $a + $b; }"

}

and receive:

{

    "explanation": "This function accepts two values..."

}

This is a simple example, but the same architecture can be extended into AI-powered documentation generators, support assistants, coding assistants and business applications.

7. Generating Images with Laravel

Laravel 13's AI SDK is not limited to text.

The SDK also provides image generation APIs.

For example:

use Laravel\Ai\Image;

$image = Image::of(

    'A modern developer workspace with multiple monitors'

)->generate();

$rawContent = (string) $image;

The result can then be saved or returned from a controller depending on your application.

This could be used for applications such as:

  • AI-generated blog illustrations
  • Product images
  • Marketing graphics
  • Educational diagrams
  • Social-media content
  • User-generated artwork

Laravel provides a common API while the underlying AI provider handles the actual generation.

8. Generating Audio

Laravel 13 also provides an API for text-to-speech workflows.

For example:

use Laravel\Ai\Audio;

$audio = Audio::of(

    'Welcome to Code Digest.'

)->generate();

$rawContent = (string) $audio;

This opens possibilities for:

  • AI narrators
  • Accessibility features
  • Voice assistants
  • Podcast generation
  • Educational applications
  • Audio versions of articles

A technology magazine could, for example, generate an audio version of an article from its existing text.

9. Embeddings: Turning Text into Vectors

One of the more important AI concepts introduced into Laravel's developer experience is embeddings.

An embedding converts text into a numerical representation that captures semantic meaning.

For example:

"How do I create a Laravel API?"

and:

"Building REST APIs with Laravel"

contain different words but have similar meaning.

Traditional keyword search may not recognize that relationship.

Semantic search can.

Laravel allows embeddings to be generated from strings:

use Illuminate\Support\Str;

$embedding = Str::of(

    'Laravel is a PHP framework for web application development.'

)->toEmbeddings();

The resulting vector can be stored and later compared against other vectors.

10. Building Semantic Search

Let's imagine Code Digest has thousands of articles.

A traditional search might work like:

SELECT *

FROM articles

WHERE title LIKE '%Laravel%';

This works for exact words, but it doesn't understand meaning.

A reader searching:

How can I protect my Laravel application from malicious requests?

might actually be looking for an article titled:

Understanding Request Forgery Protection in Laravel

The search terms are different, but their meaning is related.

Vector search can help bridge that gap.

11. Creating a Vector Column

Laravel 13 supports vector columns for supported database configurations.

For example:

Schema::ensureVectorExtensionExists();

Schema::create('documents', function (Blueprint $table) {

    $table->id();

    $table->string('title');

    $table->text('content');

    $table->vector(

        'embedding',

        dimensions: 1536

    )->index();

    $table->timestamps();

});

The Laravel documentation notes that vector queries are supported on PostgreSQL with pgvector and MariaDB 11.7 or later.

The number of dimensions must correspond to the embedding model you use.

12. Casting the Vector in Eloquent

Your model can use Laravel's AsVector cast:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\Casts\AsVector;

class Document extends Model

{

    protected function casts(): array

    {

        return [

            'embedding' => AsVector::class,

        ];

    }

}

This makes working with vector values more natural within Eloquent.

13. Searching by Meaning

Once documents have embeddings, Laravel provides vector similarity queries.

For example:

$documents = Document::query()

    ->whereVectorSimilarTo(

        'embedding',

        'How do I build Laravel applications?'

    )

    ->limit(10)

    ->get();

Notice that we aren't necessarily searching for the exact words stored in the documents.

We are asking the database to find documents whose vector representations are semantically similar.

Laravel can also accept an existing embedding:

$documents = Document::query()

    ->whereVectorSimilarTo(

        'embedding',

        $queryEmbedding,

        minSimilarity: 0.4

    )

    ->limit(10)

    ->get();

Laravel's current documentation supports similarity thresholds and vector-distance queries for more advanced search implementations.

14. Building a Simple RAG Application

This becomes particularly interesting when combined with AI agents.

Suppose Code Digest stores its articles in a database.

We could build the following workflow:

This is commonly referred to as Retrieval-Augmented Generation (RAG).

Laravel's AI SDK includes a SimilaritySearch tool that can allow an agent to search documents stored using vector embeddings.

For example:

use App\Models\Document;

use Laravel\Ai\Tools\SimilaritySearch;

public function tools(): iterable

{

    return [

        SimilaritySearch::usingModel(

            Document::class,

            'embedding'

        ),

    ];

}

Now the AI agent can retrieve relevant application data before generating its response.

This is considerably more useful than simply sending every question directly to an AI model.

15. JSON:API Resources

Laravel 13 also introduces first-party JSON:API resources.

JSON:API is a specification for structuring APIs consistently.

For example, an API might return:

{

    "data": {

        "type": "articles",

        "id": "101",

        "attributes": {

            "title": "Building APIs with Laravel",

            "published": true

        }

    }

}

Laravel's JSON:API resources handle things such as:

  • Resource serialization
  • Relationships
  • Sparse fieldsets
  • Links
  • JSON:API response headers

This can be particularly useful when building APIs consumed by:

  • Vue applications
  • React applications
  • Mobile applications
  • Third-party clients
  • Microservices

Laravel 13 makes these capabilities part of the framework rather than requiring developers to build the serialization layer themselves.

16. PHP Attributes in Controllers

Laravel 13 continues expanding its use of PHP attributes.

Instead of putting all behavior in separate configuration files or method chains, some behavior can now be declared directly on classes and methods.

For example:

use Illuminate\Routing\Attributes\Controllers\Middleware;

use Illuminate\Routing\Attributes\Controllers\Authorize;

#[Middleware('auth')]

class CommentController

{

    #[Middleware('subscribed')]

    #[Authorize('create', [Comment::class, 'post'])]

    public function store(Post $post)

    {

        // Store comment...

    }

}

The controller itself communicates important security and authorization requirements.

A developer looking at the class can immediately see that authentication is required.

Laravel 13 also introduces queue-related attributes such as:

#[Tries(3)]

#[Backoff(10)]

#[Timeout(120)]

This allows configuration to live closer to the code it controls.

17. Queue Routing by Job Class

Laravel applications frequently use queues for tasks such as:

  • Sending emails
  • Processing videos
  • Generating reports
  • Processing payments
  • Generating AI responses
  • Sending notifications

Laravel 13 introduces class-based queue routing.

For example:

use Illuminate\Support\Facades\Queue;

Queue::route(

    ProcessPodcast::class,

    connection: 'redis',

    queue: 'podcasts'

);

Now Laravel can route this particular job class to the specified connection and queue.

This becomes especially useful as an application grows.

Instead of scattering queue configuration throughout the application, related routing rules can be centralized.

18. Extending Cache Lifetime with Cache::touch()

Laravel 13 also adds:

Cache::touch(...)

This allows an existing cache item's TTL to be extended without retrieving the value and storing it again.

This is useful for applications where an item should remain cached while it is actively being used.

Conceptually:

Cached item

     ↓

User accesses item

     ↓

Extend TTL

     ↓

Keep item available

This can reduce unnecessary cache reads and writes in appropriate workloads.

19. Improved Request Forgery Protection

Security is another area that received attention in Laravel 13.

The framework's request-forgery middleware is now formalized as:

PreventRequestForgery

It also adds origin-aware verification using the Sec-Fetch-Site header while retaining compatibility with token-based CSRF protection.

For example:

use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;

When upgrading an existing application, developers should pay attention to direct references to the older:

VerifyCsrfToken

and update them where necessary.

Laravel's upgrade documentation specifically identifies request-forgery protection as a high-impact upgrade area.

20. Upgrading an Existing Laravel 12 Application

If you already have a Laravel 12 application, upgrading should begin with the official Laravel 13 upgrade guide rather than immediately changing dependencies.

First create a backup and commit your current code:

git add .

git commit -m "Before Laravel 13 upgrade"

Then review your composer.json.

Your framework dependency should move from:

"laravel/framework": "^12.0"

to:

"laravel/framework": "^13.0"

Your PHP requirement should also support PHP 8.3:

"php": "^8.3"

Then update Composer:

composer update

Run the application's test suite:

php artisan test

Also check:

php artisan route:list

and verify your application manually.

21. What Developers Should Check During the Upgrade

Laravel's official upgrade guide identifies several areas that deserve attention, including dependency updates, request-forgery protection, cache serialization, database upsert() behavior and other lower-impact changes.

A practical upgrade checklist is:

[ ] Backup database

[ ] Commit existing code

[ ] Upgrade PHP to 8.3+

[ ] Update laravel/framework

[ ] Update compatible packages

[ ] Review request-forgery changes

[ ] Review database upsert behavior

[ ] Run migrations

[ ] Run automated tests

[ ] Test authentication

[ ] Test API endpoints

[ ] Test queues

[ ] Test scheduled tasks

[ ] Test production configuration

Do not assume that a successful composer update means the upgrade is complete.

An application can successfully install Laravel 13 while still having behavioral or integration problems that only appear when its own features are exercised.

22. Laravel 13 and AI: What Has Changed?

The most significant conceptual change is arguably the position AI now occupies within the Laravel ecosystem.

Previously, a Laravel application might look like:

Laravel 13 provides more framework-level building blocks:

The result is that AI functionality can be implemented using familiar Laravel concepts and application structures.

Laravel's March 2026 product update specifically describes Laravel 13 as bringing first-party AI tooling alongside JSON:API resources, vector/semantic search and expanded PHP attributes.

23. A Practical Code Digest Project

To put several of these features together, imagine we build a small application called Code Digest Assistant.

The application contains articles about:

Laravel

PHP

Java

Spring Boot

AWS

JavaScript

Vue.js

Docker

A user enters:

How can I make my Laravel API understand natural-language searches?

The application could:

Step 1 — Create an embedding

$queryEmbedding = Str::of(

    $request->input('query')

)->toEmbeddings();

Step 2 — Search the article database

$articles = Article::query()

    ->whereVectorSimilarTo(

        'embedding',

        $queryEmbedding,

        minSimilarity: 0.4

    )

    ->limit(5)

    ->get();

Step 3 — Give the results to an AI agent

$response = (new CodeAssistant)

    ->prompt($request->input('query'));

Step 4 — Return the answer

return response()->json([

    'answer' => (string) $response,

    'sources' => $articles,

]);

This combines several Laravel 13 concepts:

That is where Laravel 13 becomes particularly interesting: individual features can be combined to create complete AI-powered applications.

24. Laravel 13 Is More Than an AI Release

Although AI receives considerable attention in Laravel 13, the release shouldn't be viewed purely as an AI framework update.

The release also improves areas that traditional Laravel applications depend on:

  • Security
  • Queues
  • Caching
  • API development
  • Eloquent
  • PHP attributes
  • Database integrations
  • Search

The September 2026 Laravel changelog also shows continued work on semantic and hybrid search, MariaDB vector queries, Eloquent vector casting, AI provider configuration and queue behavior.

This means Laravel 13 is not simply adding an AI API on top of the framework. AI-related capabilities are increasingly being connected to Laravel's existing application architecture.

Conclusion

Laravel 13 represents an important step in the evolution of the framework.

The minimum PHP requirement moves to PHP 8.3, while developers gain a first-party AI SDK capable of handling agents, text generation, embeddings, images, audio, tools and vector stores.

At the same time, Laravel continues improving the fundamentals developers rely on every day, including API resources, queues, caching, PHP attributes and security.

For developers building conventional web applications, the upgrade can be relatively straightforward. For developers building AI-powered applications, however, Laravel 13 provides a much broader set of native building blocks.

The most interesting development is therefore not any individual API.

Official references

Laravel 13 Release Notes
Laravel AI SDK Documentation
Laravel 13 Upgrade Guide

 

Tags: Laravel 13, PHP, Laravel AI SDK, Laravel AI, Vector Search, Semantic Search, PHP 8.3, JSON API, Laravel 13 Tutorial, Web Development