Most Laravel products we are asked to look at are not broken. They work, customers use them, and revenue depends on them. But they carry years of quick fixes: an old framework version, controllers that grew to two thousand lines, queue jobs that silently fail, and a test suite nobody runs. Then the business asks for AI features, and the team realizes the foundation needs attention first. This guide explains how we add AI to a Laravel application without putting the existing product at risk: audit and fix, fine-tune, then build AI on top of a stable base.
Everything below applies equally to plain PHP applications and older Laravel code. The tools differ slightly, but the order of work is the same.
Step 1: Audit What You Already Have
We start every engagement with a written code audit. It usually takes one to two weeks, depending on the size of the codebase, and it answers a simple question: what is risky, what is slow, and what is in the way of new features?
What the audit covers
- Versions and dependencies. Laravel version, PHP version, and every Composer package. We run composer outdated and composer audit to find packages with known security advisories or abandoned maintainers.
- Security. Mass assignment gaps, missing authorization policies, raw SQL with user input, secrets committed to the repository, debug mode left on, weak session and CORS settings, and file uploads stored in public paths.
- Code health. We run Larastan (PHPStan for Laravel) and Laravel Pint to measure type safety and style, and look for fat controllers, business logic inside Blade views, and duplicated code across services.
- Performance. We profile real requests with Laravel Telescope or Debugbar in a staging copy, and check slow query logs. N+1 queries, missing indexes and synchronous email or PDF generation inside web requests are the usual suspects.
- Queues and scheduled jobs. Which jobs fail, how often they retry, whether failed jobs are stored, and whether anything watches them.
- Integrations. Payment gateways, ERPs, CRMs, shipping APIs and webhooks. We check timeouts, retries, idempotency and error handling, because broken integrations are often where money leaks.
- Tests and deployment. Test coverage of critical paths, how code reaches production, and whether rollbacks are possible.
The output is a prioritized list: critical security issues, quick performance wins, structural problems, and a recommended upgrade path. You keep the report whether or not you continue with us.
Step 2: Quick Wins in the First Weeks
Some fixes are cheap and pay back immediately. We do these first so the business sees progress while the deeper work is planned.
- Fix N+1 queries with eager loading (with() and load()) and turn on Model::preventLazyLoading() in non-production environments so new ones are caught early.
- Add missing database indexes on foreign keys and columns used in filters, sorting and joins.
- Move slow work to queues. Emails, PDF generation, image processing, exports and third-party API calls belong in queued jobs, not inside the request.
- Cache expensive reads with Redis and Cache::remember(), plus route, config and view caching in production.
- Patch security issues: update vulnerable packages, rotate leaked keys, add authorization policies and rate limiting on login and public APIs.
Step 3: Upgrade and Stabilize
Upgrading Laravel and PHP
Jumping several Laravel versions at once is where teams get hurt. We upgrade one major version at a time, on a branch, with tests guarding each step. Laravel Shift automates much of the mechanical work, and Rector handles PHP syntax upgrades such as typed properties, constructor property promotion, enums, match expressions and readonly properties. Each step is deployed to staging, tested, and released before the next one starts.
Moving to a current PHP version is often the single biggest free performance gain available, and it is also a security requirement once old versions stop receiving patches. We check every extension and package for compatibility before switching.
Queues and Horizon
If the app uses Redis queues, we install Laravel Horizon for a dashboard of throughput, wait times and failed jobs. We separate queues by priority (for example, payments, notifications and reports), set sensible timeouts and retry backoff, and make jobs idempotent so a retry never charges a customer twice. This queue setup becomes important later, because AI calls are slow and must run in the background.
Tests where they matter
We do not chase coverage numbers. We write Pest or PHPUnit feature tests for the flows that make money or cause support tickets: signup, checkout, billing, permissions and key integrations. HTTP fakes (Http::fake()) and queue fakes keep tests fast and stable.
CI/CD and observability
A GitHub Actions or GitLab CI pipeline runs Pint, Larastan and tests on every pull request, then deploys with zero-downtime tools such as Laravel Forge, Envoyer, Deployer or a container pipeline on AWS. We add error tracking with Sentry or Flare, structured logs, uptime checks and Laravel Pulse for slow requests and queries. From this point, regressions show up in minutes rather than in customer emails.
Step 4: Add AI Features the Laravel Way
Once the app is stable, AI features become ordinary Laravel code: service classes, queued jobs, events and tests. That is the key point. AI should not be a separate experiment bolted onto the side of your product.
The building blocks
- LLM client. openai-php/laravel is a solid client for OpenAI models. Prism gives a single Laravel-style API over several providers, including OpenAI, Anthropic and local models through Ollama, so you can switch models without rewriting features.
- Queued AI jobs. Every non-interactive AI call runs in a Laravel job on its own queue, with rate limiting (RateLimited middleware), retries with backoff and a timeout. Results are stored in the database and broadcast to the UI with Laravel Reverb or polling.
- Vector search. For PostgreSQL apps we add the pgvector extension and store embeddings next to your existing data. For MySQL apps, Meilisearch or Typesense with hybrid search, connected through Laravel Scout, is often simpler than a new database.
- Prompt and output handling. Prompts live in versioned files or classes, not inline strings. We request structured JSON output, validate it with Laravel validation rules, and reject anything that does not fit the schema.
Example AI features we build in Laravel
- Semantic search. Customers search products, articles or records by meaning instead of exact keywords. A model observer queues an embedding job whenever a record changes, and the search endpoint combines vector similarity with your existing filters and permissions.
- RAG over your app data. An assistant answers questions from your help docs, policies, orders or knowledge base. We chunk documents, embed them into pgvector, retrieve the most relevant chunks for each question, and pass them to the model with clear instructions to answer only from that context and cite the source. See our RAG development services for how we design retrieval.
- Document and email automation. Invoices, purchase orders or inbound emails are parsed into structured fields, validated, and pushed into your existing models for a human to approve.
- Admin copilots. Support and operations staff get draft replies, ticket summaries and suggested next actions inside your Laravel admin panel (Filament or Nova), always editable before sending.
- Tool-calling agents. An assistant that can call a small set of your own actions, such as checking an order status or creating a draft refund, through Laravel policies so it can never do more than the logged-in user could.
For broader options beyond Laravel, our AI integration services page covers how we connect models to existing business systems.
Step 5: Monitor, Evaluate and Control Cost
AI features need the same operational care as payments. We log every model call with the prompt version, model, token counts, latency and outcome, and show cost per feature on a simple dashboard. A small evaluation set of real questions and expected answers runs in CI, so a prompt change or model switch that makes answers worse fails the build instead of reaching users.
Risks and How We Handle Them
- Data privacy. We send the minimum data needed, strip or mask personal details where possible, use provider settings that exclude your data from training, and keep a record of which data goes to which provider. For sensitive workloads, a self-hosted model is an option.
- Cost control. Per-user and per-feature rate limits, caching of repeated answers, smaller models for simple tasks, and hard monthly budget alerts.
- Hallucinations. Retrieval grounding, citations, structured output with validation, and a clear fallback answer when the model is not confident. Anything that changes money or customer data requires human approval.
- Prompt injection. User content and retrieved documents are treated as untrusted input. Tool calls go through the same authorization policies as the rest of the app.
- Vendor lock-in. Prism or a thin internal interface keeps the provider swappable.
Checklist Before You Add AI to Laravel
- Laravel and PHP on supported versions, with no known vulnerable packages.
- Queues monitored with Horizon, with failed jobs stored and alerted.
- Feature tests for the flows that make money.
- CI pipeline with static analysis, tests and zero-downtime deploys.
- Error tracking and slow query monitoring in production.
- A clear first AI use case with a measurable outcome, such as fewer support tickets or faster data entry.
- A data privacy decision on what may be sent to which model provider.
- Budget limits and an evaluation set in place before launch.
How Ecomsolver Works With Existing Laravel Teams
We have been building and maintaining PHP and Laravel products for more than seven years, for clients in the USA, UK, Europe, Australia and India. You can bring us in for a one-time audit and upgrade, ongoing Laravel development, or a dedicated engineer through hire a Laravel developer. Every engagement comes with an NDA, a written fixed quote, milestone payments, weekly demos, direct developer access and 100% code ownership.
Want to know where your Laravel or PHP app stands before you invest in AI? Contact us for a free code audit consultation and we will tell you what to fix first, what to upgrade, and which AI feature will pay back fastest.