Building a REST API with PHP used to mean writing endless boilerplate. You would manually map request data to database columns. You would write complex validation logic for every field. Adding artificial intelligence to that stack often meant wrestling with fragmented SDKs and inconsistent API wrappers.
The Laravel AI SDK changes that workflow. It provides a first-party, opinionated way to integrate large language models (LLMs) into your application. You can now build intelligent endpoints that return structured, validated JSON in minutes.
This guide covers how to leverage this new PHP web framework feature to ship AI-powered features faster.
The Shift to AI Agents
Modern AI integration has moved beyond simple chat completions. In the Laravel ecosystem, we use Agents.
An Agent is a dedicated PHP class. It encapsulates system instructions, conversation context, and output schemas. This structure keeps your controllers clean. It makes your AI logic reusable across your entire application.
Instead of writing a long prompt inside a controller, you define the Agent's personality and rules once. You then prompt it whenever you need a response. This abstraction is similar to how Laravel handles mailables or queued jobs.
Step 1: Install the AI SDK
Start by adding the official AI SDK to your project. This package provides a unified API for providers like OpenAI, Anthropic, and Gemini.
composer require laravel/ai
After installation, publish the configuration and migrations. These migrations create the necessary tables for storing conversation history. This is vital if you want your API to remember previous user interactions.
php artisan vendor:publish --provider="Laravel\AI\AIServiceProvider"
php artisan migrate
Set your API keys in your .env file. The SDK supports multiple providers out of the box. You can switch between them without changing your application code.

Step 2: Create a Structured Agent
A standard REST API requires predictable data. You cannot rely on free-form text from an LLM. To build a rest api with php that external services can consume, you need structured output.
Use the Artisan command to generate a new agent with a structured schema.
php artisan make:agent AnalyzeLeadAgent --structured
This command creates a class in your app/AI/Agents directory. Open the file and define the instructions and schema. The schema method uses a standard JSON schema format to define exactly what your API will return.
namespace App\AI\Agents;
use Laravel\AI\Contracts\Agent;
use Laravel\AI\Contracts\HasStructuredOutput;
class AnalyzeLeadAgent implements Agent, HasStructuredOutput
{
public function instructions(): string
{
return "You are a lead qualification assistant. Analyze the user's inquiry and categorize it.";
}
public function schema(): array
{
return [
'type' => 'object',
'properties' => [
'score' => ['type' => 'integer', 'minimum' => 0, 'maximum' => 100],
'category' => ['type' => 'string', 'enum' => ['sales', 'support', 'spam']],
'summary' => ['type' => 'string'],
],
'required' => ['score', 'category', 'summary'],
];
}
}
By implementing HasStructuredOutput, you ensure the model returns a valid JSON object. The SDK handles the heavy lifting of forcing the model to follow this schema.
Step 3: Define the API Route
Now, expose this agent through a standard Laravel route. Open your routes/api.php file and add a POST endpoint.
use App\Http\Controllers\LeadController;
use Illuminate\Support\Facades\Route;
Route::post('/leads/analyze', [LeadController::class, 'analyze']);
Next, create the controller. You can inject the agent directly into your controller method. Laravel's service container handles the instantiation for you.
namespace App\Http\Controllers;
use App\AI\Agents\AnalyzeLeadAgent;
use Illuminate\Http\Request;
class LeadController extends Controller
{
public function analyze(Request $request, AnalyzeLeadAgent $agent)
{
$request->validate(['message' => 'required|string']);
$response = $agent->prompt($request->input('message'));
return response()->json($response->structured());
}
}
The structured() method returns the validated PHP array based on your agent's schema. You can now return this directly as a JSON response. Your API is now intelligent, type-safe, and ready for production.

Enhancing the Workflow with Laravel Boost
Building the API is only half the battle. Maintaining it and ensuring it follows framework best practices is the other half. This is where Laravel Boost becomes essential.
Laravel Boost is one of the most powerful php developer tools in your arsenal. It is an MCP (Model Context Protocol) server that provides AI coding assistants with deep context about your project.
How Boost Works
Boost indexes your entire codebase, including models, routes, and database schemas. It also includes a documentation API with over 17,000 version-specific entries.
When you use an AI coding tool like Cursor or Claude Code, Boost ensures the agent knows exactly which Laravel version you are using. It prevents the AI from suggesting outdated APIs or hallucinating non-existent features.
Why You Need It
- Context Gap Fix: LLMs are trained on general PHP data. Boost gives them project-specific data.
- Protocol Compliance: It nudges AI agents to follow Laravel conventions, like using the correct Eloquent methods.
-
Tinker Integration: Agents can run
php artisan tinkercommands to inspect your database and create test fixtures during development.
Boost is a dev-only dependency. It does not affect your production performance. It simply makes building AI features more accurate and less frustrating.

Scalability and Monitoring
Once your AI-powered REST API is live, you need to monitor its performance. AI calls can be slow or prone to rate limits.
Laravel Cloud offers managed infrastructure specifically optimized for these workloads. You can use tools like Nightwatch for real-time monitoring and logs. If a provider like OpenAI goes down, the AI SDK's failover features allow you to automatically switch to Anthropic or Gemini without manual intervention.
For high-volume APIs, consider using the SDK's built-in queueing. You can prompt an agent in the background and use WebSockets to push the result back to the user once it's ready. This prevents your API from timing out during long AI generations.
Moving Forward
The combination of the Laravel AI SDK and Laravel Boost represents a new era for PHP developers. We are no longer just building websites; we are orchestrating intelligent agents.
The philosophy is simple: keep it elegant. Use the SDK to build your user-facing features. Use Boost to stay productive. Trust the ecosystem to handle the deployment and monitoring.
We would love to see what you build. Whether it is an automated support system or a complex data extraction tool, the next wave of web applications will be powered by AI and built on Laravel.
Explore the AI SDK documentation to dig deeper into tool calling and file attachments. Your story belongs here.