M
MeshWorld.
Laravel Legacy Migration AI Integration Laravel 10 Laravel 11 11 min read

Adding AI to Existing Laravel Projects: 10, 11, and 12 Upgrade Guide

Darsh Jariwala
By Darsh Jariwala
| Updated: Apr 9, 2026

Your application runs on Laravel 10 or 11. It has years of accumulated code, custom packages, and business logic that nobody wants to touch. The team wants AI features now, not after a six-month upgrade project.

Good news: you can add AI capabilities without upgrading to Laravel 13. Most AI integration happens at the service layer, completely separate from framework internals. OpenAI and Claude don’t care which Laravel version you run.

This guide shows how to integrate AI into existing Laravel 10 and 11 applications, what requires upgrading, what works as-is, and how to plan a gradual migration if you need newer features.

:::note[TL;DR]

  • AI packages work on Laravel 10, 11, 12, and 13 with the same syntax
  • Laravel Boost supports 10+ for AI-assisted development
  • Upgrade only when you need Laravel 13-specific AI features (AI SDK, Chronicle)
  • Most AI integration is service-layer code, unaffected by framework version
  • Test thoroughly when adding AI to legacy code with complex business rules :::

What Works on Laravel 10 and 11?

The core AI integration stack works identically across Laravel 10, 11, 12, and 13:

FeatureLaravel 10Laravel 11Laravel 12+Notes
openai-php/laravelSame API across all versions
laravel-anthropicNo version-specific dependencies
Vector search with pgvectorDatabase feature, not framework
Laravel Reverb✅ 10.33+May need version constraint
Laravel BoostAI dev tool, works on 10+
Livewire 3 streamingSame component syntax

Real scenario: Your Laravel 10 e-commerce app from 2022 can get AI product descriptions, customer support chat, and recommendation engines without touching a single framework file. The AI service classes sit in app/Services/ and call APIs exactly like they would on Laravel 13.

How Do I Add AI Without Upgrading?

Step 1: Install AI Packages

The OpenAI and Anthropic packages have no Laravel version constraints beyond basic framework features:

composer require openai-php/laravel
composer require sixlive/laravel-anthropic

Both work on Laravel 10.10+ and PHP 8.1+. If you’re on older PHP versions, upgrade PHP first (PHP 8.1 is minimum for most AI packages).

Step 2: Create Service Classes

Keep AI logic in dedicated services, not scattered through controllers:

<?php

namespace App\Services;

use OpenAI\Laravel\Facades\OpenAI;

class LegacyAiService
{
    private const MAX_TOKENS = 2000;
    private const CACHE_TTL = 3600;

    public function generateProductDescription(array $productData): string
    {
        $cacheKey = "ai_desc:{$productData['id']}";

        return cache()->remember($cacheKey, self::CACHE_TTL, function () use ($productData) {
            $response = OpenAI::chat()->create([
                'model' => 'gpt-4o-mini',
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => 'Generate compelling e-commerce product descriptions.'
                    ],
                    [
                        'role' => 'user',
                        'content' => $this->buildProductPrompt($productData)
                    ]
                ],
                'max_tokens' => self::MAX_TOKENS,
            ]);

            return $response->choices[0]->message->content;
        });
    }

    private function buildProductPrompt(array $data): string
    {
        return <<<PROMPT
Product: {$data['name']}
Category: {$data['category']}
Features: {$data['features']}
Target audience: {$data['audience']}

Write a 2-paragraph product description highlighting benefits, not just features.
PROMPT;
    }
}

This service works identically on Laravel 10, 11, 12, or 13.

Step 3: Add to Existing Controllers

Drop AI features into existing controller methods:

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Services\LegacyAiService;

class ProductController extends Controller
{
    public function __construct(
        private LegacyAiService $aiService
    ) {}

    public function show($id)
    {
        $product = Product::findOrFail($id);

        // Generate AI description if missing or outdated
        if (empty($product->ai_description) || $product->updated_at->diffInDays(now()) > 30) {
            $product->ai_description = $this->aiService->generateProductDescription($product->toArray());
            $product->save();
        }

        return view('products.show', compact('product'));
    }

    public function generateDescription($id)
    {
        $product = Product::findOrFail($id);

        // Authorization check - use your existing policy
        $this->authorize('update', $product);

        $description = $this->aiService->generateProductDescription($product->toArray());

        return response()->json([
            'description' => $description,
            'generated_at' => now()->toIso8601String(),
        ]);
    }
}

No framework changes needed. Your existing routing, middleware, and authorization work exactly as before.

What Requires Laravel 12 or 13?

Some AI features need newer framework capabilities:

FeatureMinimum VersionWhy
Laravel AI SDK13.xFirst-party SDK requires 13+
Chronicle13.xNew database feature
Type-safe containers12.xPHP 8.3 typed dependencies
Laravel Boost (full)10.x+Works on 10+, some features need newer versions
Native enum stringable12.xStringable enum methods

When to upgrade:

  • Building AI-heavy applications from scratch → Start on Laravel 13
  • Need Chronicle for AI-driven database features → Upgrade to 13
  • Large existing app with minimal AI needs → Stay on current version

How Do I Use Laravel Boost on Older Versions?

Laravel Boost officially supports Laravel 10, 11, 12, and 13. Installation is identical:

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

The installer detects your Laravel version and adjusts accordingly:

  • Laravel 10/11: Full Boost tools work, but some newer introspection features may be limited
  • Laravel 12/13: Complete feature set including latest documentation search and AI guidelines

Using Boost with Laravel 10:

# In Claude Code or Cursor with Laravel 10 project
> Create a migration for user preferences

# Boost provides context about your Laravel 10 structure
# Agent generates migration compatible with Laravel 10 schema

The agent knows your Laravel version and generates appropriate code. It won’t suggest Laravel 13 syntax for a Laravel 10 project.

How Do I Handle Breaking Changes When Upgrading?

If you decide to upgrade for better AI features, minimize risk:

Upgrade Path: Laravel 10 → 11 → 12 → 13

10 to 11 (Minimal breaking changes):

  • New skeleton structure (optional)
  • Default database switched to SQLite (configurable)
  • Model structure changes (minor)

11 to 12 (Maintenance release):

  • Minimal breaking changes
  • New starter kits available
  • Chronicle preview (became stable in 13)

12 to 13 (AI-focused):

  • Laravel AI SDK introduced
  • Agent skills formalized
  • Enhanced MCP support

Gradual Migration Strategy

Don’t upgrade the entire app at once:

# Option 1: Greenfield AI microservice
# Create new Laravel 13 app for AI features
# API communication with existing Laravel 10 app

# Option 2: Gradual component extraction
# Move AI-heavy features to Laravel 13 service
# Keep core business logic on current version

Example: Extracting AI recommendations

Your Laravel 10 monolith calls a Laravel 13 microservice:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class AiRecommendationClient
{
    private string $baseUrl;

    public function __construct()
    {
        $this->baseUrl = config('services.ai_recommendations.url');
    }

    public function getRecommendations(int $userId, int $count = 5): array
    {
        $response = Http::withToken(config('services.ai_recommendations.token'))
            ->post("{$this->baseUrl}/api/recommendations", [
                'user_id' => $userId,
                'count' => $count,
                'context' => $this->getUserContext($userId),
            ]);

        return $response->json('recommendations', []);
    }

    private function getUserContext(int $userId): array
    {
        // Query your Laravel 10 database
        return [
            'recent_purchases' => \DB::table('orders')
                ->where('user_id', $userId)
                ->latest()
                ->limit(5)
                ->pluck('product_category'),
            'browsing_history' => cache()->get("user:{$userId}:recent_views", []),
        ];
    }
}

The Laravel 13 service handles AI logic with the latest features. Your Laravel 10 app continues running core business operations.

What About PHP Version Requirements?

AI packages have PHP 8.1+ requirements. If you’re on PHP 7.4 or 8.0, upgrade PHP first:

Your PHPAction Required
7.4Upgrade to PHP 8.1+ (Laravel 10 requires 8.1)
8.0Upgrade to PHP 8.1+
8.1Ready for Laravel 10, 11, 12, 13
8.2Optimal for Laravel 11+
8.3Required for Laravel 13 type-safe features

PHP upgrade without Laravel upgrade:

# Upgrade PHP on server first
# Most Laravel 10 code works on PHP 8.3
# Then gradually adopt PHP 8.3 features (typed class constants, etc.)

How Do I Test AI Integration in Legacy Code?

Legacy applications often lack test coverage. Adding AI makes this worse if you don’t test the integration:

<?php

namespace Tests\Feature;

use App\Models\Product;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class LegacyAiIntegrationTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        // Prevent real API calls
        Http::preventStrayRequests();
    }

    public function test_ai_description_generated_for_empty_products(): void
    {
        Http::fake([
            'api.openai.com/*' => Http::response([
                'choices' => [
                    ['message' => ['content' => 'AI-generated product description']]
                ],
                'usage' => ['total_tokens' => 100],
            ]),
        ]);

        $product = Product::factory()->create([
            'name' => 'Test Widget',
            'ai_description' => null,
        ]);

        $response = $this->actingAs($this->adminUser)
            ->get("/products/{$product->id}");

        $response->assertOk();

        // Verify AI description was generated and saved
        $product->refresh();
        $this->assertNotNull($product->ai_description);
        $this->assertStringContains('AI-generated', $product->ai_description);

        // Verify API was called
        Http::assertSentCount(1);
    }

    public function test_ai_generation_respects_rate_limits(): void
    {
        Http::fake([
            'api.openai.com/*' => Http::response([
                'choices' => [['message' => ['content' => 'Description']]]
            ]),
        ]);

        // Simulate rate limit by calling multiple times
        for ($i = 0; $i < 15; $i++) {
            $response = $this->actingAs($this->user)
                ->postJson("/products/" . ($i + 1) . "/generate-description");
        }

        // Last request should be rate limited
        $response->assertStatus(429);
    }

    public function test_ai_service_handles_legacy_product_data(): void
    {
        // Test with legacy data structure
        $legacyProduct = [
            'id' => 123,
            'name' => 'Legacy Product',
            'category' => 'Uncategorized', // Legacy default
            'features' => null, // Legacy null field
            'audience' => 'general',
        ];

        $service = app(\App\Services\LegacyAiService::class);

        Http::fake([
            'api.openai.com/*' => Http::response([
                'choices' => [
                    ['message' => ['content' => 'Description for legacy product']]
                ],
            ]),
        ]);

        $description = $service->generateProductDescription($legacyProduct);

        $this->assertNotEmpty($description);
    }
}

Common Pitfalls in Legacy Integration

1. Missing validation on AI outputs

Legacy code may trust database content. AI-generated content needs the same validation as user input:

// Bad: Saving AI output directly
$product->description = $aiResponse;
$product->save();

// Good: Validate and sanitize
$validated = strip_tags($aiResponse); // Remove unwanted HTML
$product->description = substr($validated, 0, 5000); // Enforce limits
$product->save();

2. No error handling for API failures

Legacy apps often assume external services work. AI APIs fail regularly (rate limits, timeouts, downtime):

// Add fallback in your service
public function generateWithFallback(array $data): string
{
    try {
        return $this->generateProductDescription($data);
    } catch (\Exception $e) {
        // Log error
        \Log::error('AI generation failed', ['error' => $e->getMessage()]);

        // Return manual description or cached version
        return $data['manual_description'] ?? 'Description coming soon.';
    }
}

3. N+1 queries from AI service calls

If you call AI during model loops, you’ll hit performance issues:

// Bad: AI call in a loop
foreach (Product::all() as $product) {
    $product->ai_description = $aiService->generate($product); // API call per product!
}

// Good: Batch processing with queue
Product::chunk(100, function ($products) {
    foreach ($products as $product) {
        dispatch(new GenerateAiDescription($product));
    }
});

When Should I Upgrade vs. Stay Put?

Stay on current version if:

  • AI is a minor feature (few API calls per day)
  • Legacy code is stable and well-tested
  • Team has limited upgrade bandwidth
  • PHP version already supports AI packages

Upgrade to Laravel 13 if:

  • AI is core to your application
  • You need Chronicle for AI-driven database features
  • Starting a major rewrite anyway
  • Want first-party AI SDK support
  • Team capacity for upgrade project exists

Hybrid approach:

  • Keep core application on current Laravel
  • Extract AI services to Laravel 13 microservices
  • Gradual migration as you touch related code

Summary

  • Laravel 10 and 11 support most AI features through third-party packages
  • AI integration happens at the service layer, independent of framework version
  • Upgrade only when you need Laravel 13-specific features (AI SDK, Chronicle)
  • PHP 8.1+ is the real requirement; upgrade PHP before Laravel if needed
  • Laravel Boost works on 10+ for AI-assisted development
  • Gradual migration via microservices is safer than big-bang upgrades

FAQ

Can I use structured outputs on Laravel 10? Yes. Structured outputs are an OpenAI/Claude feature, not a Laravel feature. Works on any version.

What about vector search on Laravel 10? pgvector is a PostgreSQL extension. Works with any Laravel version that supports PostgreSQL.

Do I need Livewire 3 for AI chat interfaces? No. You can build chat with plain Laravel, Vue, React, or Alpine.js. Livewire 3 makes streaming easier but isn’t required.

How do I handle Laravel 10’s older validation with AI responses? Validate AI output like any user input. Sanitize HTML, enforce length limits, check for inappropriate content before saving.

Can I use Laravel Boost with Laravel 8 or 9? No. Boost requires Laravel 10+ and PHP 8.1+. Upgrade to at least Laravel 10 to use Boost.

Is it worth upgrading just for the Laravel AI SDK? Probably not for existing apps. The third-party packages (openai-php, laravel-anthropic) provide equivalent functionality. The AI SDK mainly standardizes patterns across providers.