<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rekha Patel on Medium]]></title>
        <description><![CDATA[Stories by Rekha Patel on Medium]]></description>
        <link>https://medium.com/@devrekha?source=rss-49f97b15a16d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*levZfuPImwFlsXHEw2meOA.png</url>
            <title>Stories by Rekha Patel on Medium</title>
            <link>https://medium.com/@devrekha?source=rss-49f97b15a16d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:35:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devrekha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI in Production with Laravel: Security, Queues, Human Approval & Reliable Workflows]]></title>
            <link>https://medium.com/@devrekha/ai-in-production-with-laravel-security-queues-human-approval-reliable-workflows-b17a23d4f0e9?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b17a23d4f0e9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-11-25T08:01:02.907Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Laravel AI Series — Part 6</em></p><p>Learn how to build safer AI applications using authorization, background jobs, human approvals, and production best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*309jbEU3iVCD94jN5PzLcQ.jpeg" /></figure><p>Building an AI feature is exciting.</p><p>We install an SDK, connect an AI provider, create an agent, add tools, and suddenly our application can answer questions and perform tasks.</p><p>But building a feature that works locally is different from building one that works reliably in production.</p><p>What happens if the AI provider is unavailable?</p><p>What if an AI agent tries to access another tenant’s data?</p><p>What if it sends an email, deletes a record, or performs an action without permission?</p><p>What happens when an AI request takes 30 seconds or fails halfway through?</p><p>These are the questions we need to answer before deploying AI features to production.</p><p>In this article, we’ll explore how to make Laravel AI applications safer and more reliable using queues, authorization, human approval, error handling, and testing.</p><h3>1. Never Trust AI Output Blindly</h3><p>AI models can generate incorrect information, misunderstand requests, or return unexpected output.</p><p>If we directly save AI-generated content into our database or execute it without validation, we create unnecessary risks.</p><p>For example, imagine an AI agent generates a quotation amount.</p><p>We should never blindly accept the generated amount as the final business value.</p><p>Instead, we should:</p><ul><li>Validate the output.</li><li>Verify calculations using PHP.</li><li>Check authorization.</li><li>Apply business rules.</li><li>Require approval when necessary.</li></ul><p>AI can help us make decisions, but our Laravel application should remain responsible for enforcing business rules.</p><p><strong>Rule of thumb: AI suggests. Laravel validates. The application decides what is allowed.</strong></p><h3>2. Protect Your Application Data</h3><p>This is especially important for SaaS applications.</p><p>Imagine a system with multiple organizations:</p><pre>Organization A<br> ├── Projects<br> ├── Tasks<br> └── Documents</pre><pre>Organization B<br> ├── Projects<br> ├── Tasks<br> └── Documents</pre><p>If an AI agent searches project data, it must only access information belonging to the authenticated organization.</p><p>Never expose unrestricted database access to an AI agent.</p><p>Instead, use tools with controlled queries.</p><p>For example:</p><pre>$projects = Project::query()<br>    -&gt;where(&#39;organization_id&#39;, auth()-&gt;user()-&gt;organization_id)<br>    -&gt;get();</pre><p>The organization filter should be enforced by Laravel — not by asking the AI to remember which organization it belongs to.</p><p>The same rule applies to:</p><ul><li>Documents</li><li>Customer records</li><li>Quotations</li><li>Tasks</li><li>Reports</li><li>Conversations</li><li>Vector search results</li></ul><p>AI must never bypass your existing authorization rules.</p><h3>3. Use Laravel Queues for Long AI Requests</h3><p>AI requests can take several seconds or even longer.</p><p>Processing large documents, generating reports, summarizing conversations, or creating embeddings may not be suitable for normal HTTP requests.</p><p>Instead of making the user wait, we can process AI requests in the background using Laravel queues.</p><p>A typical workflow:</p><pre>User Request<br>     |<br>     v<br>Laravel Application<br>     |<br>     v<br>Dispatch AI Job<br>     |<br>     v<br>Return Response Immediately<br>     |<br>     v<br>Queue Worker<br>     |<br>     v<br>AI Processing<br>     |<br>     v<br>Save Result<br>     |<br>     v<br>Notify User</pre><p>Laravel AI SDK supports queueing agent requests.</p><p>For example:</p><pre>use App\Ai\Agents\LaravelAssistant;<br>use Laravel\Ai\Responses\AgentResponse;<br>use Throwable;</pre><pre>$response = LaravelAssistant::make()<br>    -&gt;queue(&#39;Summarize this project report.&#39;)<br>    -&gt;then(function (AgentResponse $response) {<br>        // Store the generated response.<br>    })<br>    -&gt;catch(function (Throwable $exception) {<br>        // Handle the failure.<br>        report($exception);<br>    });</pre><p>The then() callback handles successful responses, while catch() provides a place to handle exceptions.</p><p>For production applications, we should also configure the queue driver, workers, retry behavior, failed jobs, and monitoring.</p><h3>4. Handle Failures Properly</h3><p>AI providers are external services.</p><p>They may experience:</p><ul><li>Rate limits</li><li>Temporary outages</li><li>Network timeouts</li><li>Invalid responses</li><li>Service errors</li><li>Unexpected costs</li></ul><p>We should never assume every AI request will succeed.</p><p>For queued jobs, configure retries and timeouts appropriately.</p><p>For example, in a Laravel job:</p><pre>public $tries = 3;</pre><pre>public $timeout = 120;</pre><p>This allows the job to retry up to three times and limits how long the job can run.</p><p>These values should be adjusted according to your AI provider, request complexity, and queue configuration.</p><p>We should also avoid retrying certain failures unnecessarily, especially when they are caused by invalid input or configuration.</p><p>For important workflows, log the failure and provide a clear status to the user.</p><h3>5. Human Approval for Sensitive AI Actions</h3><p>This is one of the most important features when building AI agents that can use tools.</p><p>Imagine an agent that can:</p><ul><li>Send emails</li><li>Delete files</li><li>Approve quotations</li><li>Update customer records</li><li>Change project deadlines</li><li>Execute financial operations</li></ul><p>Should the AI perform every action automatically?</p><p>For sensitive actions, I prefer a human approval workflow.</p><p>The process can be:</p><pre>User Request<br>     |<br>     v<br>AI Agent<br>     |<br>     v<br>Prepare Tool Action<br>     |<br>     v<br>Approval Required<br>     |<br>     v<br>Show Action Details<br>     |<br>     +---- Reject ----&gt; Stop / Explain<br>     |<br>     +---- Approve ---&gt; Execute Tool<br>                            |<br>                            v<br>                       Audit Log</pre><p>The user should be able to see exactly what the AI intends to do before approving it.</p><h3>6. Create an Approvable Tool</h3><p>Laravel AI SDK supports approvable tools.</p><p>Let’s imagine a tool that deletes a file.</p><p>Because deletion is a sensitive action, we can require approval before it executes.</p><p>A simplified tool structure looks like this:</p><pre>namespace App\Ai\Tools;</pre><pre>use Laravel\Ai\Concerns\InteractsWithApprovals;<br>use Laravel\Ai\Contracts\Approvable;<br>use Laravel\Ai\Contracts\Tool;</pre><pre>class DeleteFile implements Approvable, Tool<br>{<br>    use InteractsWithApprovals;</pre><pre>    // Define the tool description,<br>    // input schema, and handle method.</pre><pre>    // This tool requires approval<br>    // before execution by default.<br>}</pre><p>By implementing the Approvable contract and using InteractsWithApprovals, the tool can pause execution until a human decision is made.</p><p>When an agent requests this tool, Laravel can return a pending approval rather than executing the operation immediately.</p><p>This allows us to review the requested action before it happens.</p><h3>7. Inspect Pending Approvals</h3><p>When an agent pauses for approval, we can inspect the pending approval information.</p><p>For example:</p><pre>$response = (new FileAssistant)<br>    -&gt;forUser($user)<br>    -&gt;prompt(&#39;Delete the old invoice file.&#39;);</pre><pre>if ($response-&gt;hasPendingApprovals()) {</pre><pre>    foreach ($response-&gt;pendingApprovals as $approval) {</pre><pre>        // Inspect:<br>        // $approval-&gt;id<br>        // $approval-&gt;tool<br>        // $approval-&gt;arguments<br>        // $approval-&gt;reason</pre><pre>    }<br>}</pre><p>We can display this information in our frontend.</p><p>For example:</p><p><strong>AI wants to perform this action:</strong></p><pre>Action: Delete File</pre><pre>File: invoices/old-invoice.pdf</pre><pre>Reason: The user requested deletion<br>of the old invoice file.</pre><pre>[Approve] [Reject]</pre><p>The user can now make an informed decision.</p><p>The approval interface should be protected by authentication and authorization. Only the appropriate user should be allowed to approve the pending action.</p><h3>8. Resume the Agent After Approval</h3><p>After the user reviews the action, we can continue the conversation with an approval or rejection decision.</p><p>Laravel AI SDK provides approval decision classes for this workflow.</p><p>A simplified example:</p><pre>use Laravel\Ai\Approvals\Decision;<br>use Laravel\Ai\Approvals\Decisions;</pre><pre>$decisions = Decisions::from([<br>    &#39;call_abc&#39; =&gt; Decision::approve(),<br>]);</pre><pre>$response = (new FileAssistant)<br>    -&gt;continue($conversationId, as: $user)<br>    -&gt;prompt($decisions);</pre><p>Here, call_abc represents the pending tool-call ID returned by the agent.</p><p>In a real application, we should not hardcode it.</p><p>Instead, we should retrieve the pending approval ID from the stored approval state and submit the user’s decision against that specific request.</p><p>A rejection can also be provided:</p><pre>$decisions = Decisions::from([<br>    &#39;call_abc&#39; =&gt; Decision::reject(<br>        &#39;This file should not be deleted.&#39;<br>    ),<br>]);</pre><p>The agent can then receive the rejection and continue responding appropriately.</p><p><strong>Important:</strong> Approval workflows require conversation history to be available when the agent resumes. Use the SDK’s conversation support or supply the required message history according to the official documentation.</p><h3>9. Log AI Actions</h3><p>AI actions should be auditable.</p><p>For production applications, consider logging:</p><ul><li>User ID</li><li>Organization ID</li><li>Agent name</li><li>Tool name</li><li>Action requested</li><li>Approval status</li><li>Approver ID</li><li>Execution result</li><li>Timestamp</li><li>Failure details</li></ul><p>For example:</p><pre>AI Action Log</pre><pre>User: 105<br>Organization: 12<br>Agent: FileAssistant<br>Tool: DeleteFile<br>File: invoices/old-invoice.pdf</pre><pre>Approval: Approved<br>Approved By: Admin 24</pre><pre>Status: Executed<br>Time: 2026-11-20 14:45</pre><p>Avoid logging secrets, complete confidential documents, API keys, or unnecessary personal information.</p><p>Audit logs help us investigate issues, understand how AI features are being used, and improve our workflows.</p><h3>10. Test Your AI Features</h3><p>We should not rely only on manual testing.</p><p>Laravel AI SDK provides testing capabilities for agents and related AI features, including fakes.</p><p>Testing helps us verify:</p><ul><li>Agent responses</li><li>Tool usage</li><li>Expected behavior</li><li>Error handling</li><li>Application workflows</li></ul><p>For example, we should test that:</p><ul><li>A user cannot retrieve another organization’s documents.</li><li>A sensitive tool requires approval.</li><li>A rejected action does not execute.</li><li>A failed AI request is handled correctly.</li><li>Invalid AI output is not saved.</li><li>A queued AI job can fail and retry correctly.</li></ul><p>AI testing is not only about checking whether the response sounds good.</p><p>It is also about ensuring the application behaves safely.</p><h3>Production Checklist</h3><p>Before deploying an AI-powered Laravel application, I would check the following:</p><ul><li>API keys stored securely</li><li>Authentication and authorization enforced</li><li>Tenant isolation implemented</li><li>AI output validated</li><li>Sensitive tools require approval</li><li>Queue workers configured</li><li>Timeouts and retries configured</li><li>Failed jobs monitored</li><li>AI usage and costs tracked</li><li>Audit logs implemented</li><li>Rate limits applied</li><li>AI features tested</li><li>Sensitive data protected</li><li>User-facing error messages implemented</li></ul><h3>Final Thoughts</h3><p>Building AI features is not just about sending prompts to an AI model.</p><p>When AI becomes part of a real business application, we need to think about security, permissions, reliability, costs, and user trust.</p><p>Laravel gives us a familiar foundation for building these workflows using agents, tools, queues, testing, and human approval.</p><p>The most powerful AI application is not necessarily the one that can do everything automatically.</p><p>It is the one that can do useful work while respecting the application’s rules, protecting its data, and keeping humans involved when it matters.</p><p><strong>AI can make our applications smarter. Good engineering makes them trustworthy.</strong></p><p>This brings our Laravel AI series from the basics of AI integration to the concepts required for building more production-ready AI applications.</p><p>What AI feature are you building with Laravel?</p><h3>References</h3><ul><li><a href="https://laravel.com/docs/13.x/ai-sdk">Laravel AI SDK — Official Documentation</a></li><li><a href="https://laravel.com/docs/13.x/ai-sdk#queueing">Laravel AI SDK — Queueing</a></li><li><a href="https://laravel.com/docs/13.x/ai-sdk#human-tool-approval">Laravel AI SDK — Human Tool Approval</a></li><li><a href="https://laravel.com/blog/introducing-laravel-ai-sdk-v1">Laravel AI SDK v1.0 Announcement</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b17a23d4f0e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG with Laravel AI SDK: Build a Knowledge Base That Answers Questions from Your Own Data]]></title>
            <link>https://medium.com/@devrekha/rag-with-laravel-ai-sdk-build-a-knowledge-base-that-answers-questions-from-your-own-data-cbc96e2a377f?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbc96e2a377f</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-11-24T08:01:02.897Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Laravel AI Series — Part 5</em></p><p>Learn embeddings, vector search, and how to connect your Laravel AI agent to company knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLWM_mwdQW9XY0vVNZCXHw.jpeg" /></figure><p>In the previous article, we learned how to give our Laravel AI agent tools to perform specific tasks.</p><p>But what if we want our AI assistant to answer questions using our own company documents, project information, policies, or knowledge base?</p><p>For example:</p><ul><li>“What is our leave policy?”</li><li>“How many annual leaves can an employee carry forward?”</li><li>“What is the process for approving quotations?”</li><li>“Summarize our project delivery guidelines.”</li></ul><p>A normal AI model may not know the answers to these questions because the information belongs to our application or organization.</p><p>We don’t want to manually add every document to every prompt.</p><p>This is where <strong>RAG (Retrieval-Augmented Generation)</strong> comes in.</p><h3>What is RAG?</h3><p>RAG allows an AI model to retrieve relevant information from our own data before generating a response.</p><p>Instead of relying only on its trained knowledge, the AI searches our knowledge base, finds relevant content, and uses that content to answer the question.</p><p>A simple workflow looks like this:</p><pre>Upload Documents<br>       |<br>       v<br>Extract Text<br>       |<br>       v<br>Split Text into Chunks<br>       |<br>       v<br>Generate Embeddings<br>       |<br>       v<br>Store in Database<br>       |<br>       v<br>User Asks a Question<br>       |<br>       v<br>Search Relevant Content<br>       |<br>       v<br>AI Generates Answer</pre><p>Let’s build a simple version using Laravel AI SDK.</p><h3>Step 1: Understand Embeddings</h3><p>Before implementing RAG, we need to understand embeddings.</p><p>An embedding converts text into a numerical representation that captures its meaning.</p><p>For example:</p><pre>&quot;Employees can carry forward unused leave.&quot;</pre><p>and</p><pre>&quot;Unused annual leave can be transferred to the next year.&quot;</pre><p>These sentences use different words, but their meanings are similar.</p><p>Keyword search may not find a strong match. Semantic search can identify that they are related because their vector representations are similar.</p><p>This is the foundation of RAG.</p><h3>Step 2: Configure the Database</h3><p>For this example, we’ll use PostgreSQL with the pgvector extension.</p><p>Laravel’s native vector-column support makes it possible to store embeddings and perform similarity searches.</p><blockquote><em>Vector search in Laravel AI SDK currently requires a database supported by Laravel’s vector query features. PostgreSQL with pgvector is a common choice. MariaDB 11.7+ also supports native vector functionality in current Laravel documentation.</em></blockquote><h3>Step 3: Create a Documents Table</h3><p>Create a migration:</p><pre>php artisan make:migration create_documents_table</pre><p>Update the migration:</p><pre>&lt;?php</pre><pre>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;</pre><pre>return new class extends Migration<br>{<br>    public function up(): void<br>    {<br>        Schema::ensureVectorExtensionExists();</pre><pre>        Schema::create(&#39;documents&#39;, function (Blueprint $table) {<br>            $table-&gt;id();</pre><pre>            $table-&gt;string(&#39;title&#39;);<br>            $table-&gt;text(&#39;content&#39;);</pre><pre>            $table-&gt;vector(&#39;embedding&#39;, dimensions: 1536);</pre><pre>            $table-&gt;timestamps();<br>        });<br>    }</pre><pre>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;documents&#39;);<br>    }<br>};</pre><p>In this example, we use 1536 dimensions because we’ll generate embeddings using OpenAI’s text-embedding-3-small model with that dimension size.</p><p><strong>Important:</strong> The embedding model and database vector dimensions must match. If you choose another embedding model, verify its dimensions and configure the database column accordingly.</p><p>Run the migration:</p><pre>php artisan migrate</pre><h3>Step 4: Create the Document Model</h3><p>Create a model:</p><pre>php artisan make:model Document</pre><p>Update app/Models/Document.php:</p><pre>&lt;?php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Casts\AsVector;</pre><pre>class Document extends Model<br>{<br>    protected $fillable = [<br>        &#39;title&#39;,<br>        &#39;content&#39;,<br>        &#39;embedding&#39;,<br>    ];</pre><pre>    protected function casts(): array<br>    {<br>        return [<br>            &#39;embedding&#39; =&gt; AsVector::class,<br>        ];<br>    }<br>}</pre><p>The AsVector cast helps Laravel handle vector data when storing and retrieving embeddings.</p><h3>Step 5: Generate an Embedding</h3><p>Now let’s convert document text into an embedding.</p><p>Laravel AI SDK provides the Embeddings class.</p><pre>use Laravel\Ai\Embeddings;<br>use Laravel\Ai\Enums\Lab;</pre><pre>$text = &#39;Employees receive 12 paid leaves annually.&#39;;</pre><pre>$response = Embeddings::for([$text])<br>    -&gt;dimensions(1536)<br>    -&gt;generate(<br>        Lab::OpenAI,<br>        &#39;text-embedding-3-small&#39;<br>    );</pre><pre>$embedding = $response-&gt;embeddings[0];</pre><p>The $embedding variable now contains a numerical vector representing the meaning of our text.</p><p>We can store this vector in the database.</p><h3>Step 6: Store Knowledge in the Database</h3><p>For this tutorial, let’s insert a few sample knowledge-base entries.</p><pre>use App\Models\Document;<br>use Laravel\Ai\Embeddings;<br>use Laravel\Ai\Enums\Lab;</pre><pre>$documents = [<br>    [<br>        &#39;title&#39; =&gt; &#39;Annual Leave Policy&#39;,<br>        &#39;content&#39; =&gt; &#39;Employees receive 12 paid leaves annually. &#39;<br>            . &#39;Unused leave may be carried forward according &#39;<br>            . &#39;to company policy.&#39;,<br>    ],<br>    [<br>        &#39;title&#39; =&gt; &#39;Project Delivery Policy&#39;,<br>        &#39;content&#39; =&gt; &#39;Project deadlines must be reviewed by &#39;<br>            . &#39;the project lead. Delays should be communicated &#39;<br>            . &#39;to stakeholders as early as possible.&#39;,<br>    ],<br>    [<br>        &#39;title&#39; =&gt; &#39;Quotation Approval Policy&#39;,<br>        &#39;content&#39; =&gt; &#39;Quotations above the authorized approval &#39;<br>            . &#39;limit must be reviewed by the appropriate manager &#39;<br>            . &#39;before being sent to the customer.&#39;,<br>    ],<br>];</pre><pre>foreach ($documents as $item) {</pre><pre>    $response = Embeddings::for([$item[&#39;content&#39;]])<br>        -&gt;dimensions(1536)<br>        -&gt;generate(<br>            Lab::OpenAI,<br>            &#39;text-embedding-3-small&#39;<br>        );</pre><pre>    Document::create([<br>        &#39;title&#39; =&gt; $item[&#39;title&#39;],<br>        &#39;content&#39; =&gt; $item[&#39;content&#39;],<br>        &#39;embedding&#39; =&gt; $response-&gt;embeddings[0],<br>    ]);<br>}</pre><p>This example generates an embedding for each document and saves the original text alongside the vector.</p><p>For a larger knowledge base, this should be moved into a queued job rather than processing all documents during a web request.</p><h3>Step 7: Search for Relevant Documents</h3><p>Now let’s search our knowledge base.</p><p>Imagine a user asks:</p><blockquote><em>Can unused leave be transferred to the next year?</em></blockquote><p>We can perform semantic search using Laravel’s whereVectorSimilarTo() method.</p><pre>use App\Models\Document;</pre><pre>$query = &#39;Can unused leave be transferred to the next year?&#39;;</pre><pre>$documents = Document::query()<br>    -&gt;whereVectorSimilarTo(<br>        &#39;embedding&#39;,<br>        $query,<br>        minSimilarity: 0.4<br>    )<br>    -&gt;limit(5)<br>    -&gt;get();</pre><p>Laravel generates the query embedding and searches for documents with similar meanings.</p><p>The result could include our Annual Leave Policy document, even though the document doesn’t contain the exact wording of the user’s question.</p><p>This is the advantage of semantic search.</p><h3>Step 8: Give the AI Agent Access to the Knowledge Base</h3><p>Instead of manually searching for documents every time, we can give our AI agent a similarity-search tool.</p><p>Open the agent created in Part 3.</p><p>For example, LaravelAssistant.php:</p><pre>&lt;?php</pre><pre>namespace App\Ai\Agents;</pre><pre>use App\Models\Document;<br>use Laravel\Ai\Contracts\Agent;<br>use Laravel\Ai\Contracts\HasTools;<br>use Laravel\Ai\Promptable;<br>use Laravel\Ai\Tools\SimilaritySearch;</pre><pre>class LaravelAssistant implements Agent, HasTools<br>{<br>    use Promptable;</pre><pre>    public function instructions(): string<br>    {<br>        return &#39;You are a helpful company knowledge assistant.</pre><pre>                Use the knowledge base to answer questions<br>                about company policies and documentation.</pre><pre>                Base your answers on retrieved information.</pre><pre>                If the knowledge base does not contain<br>                the answer, clearly say that the information<br>                is not available.</pre><pre>                Do not invent company policies.&#39;;<br>    }</pre><pre>    public function tools(): iterable<br>    {<br>        return [<br>            SimilaritySearch::usingModel(<br>                Document::class,<br>                &#39;embedding&#39;<br>            )-&gt;withDescription(<br>                &#39;Search company documents and policies &#39;<br>                . &#39;for information relevant to the question.&#39;<br>            ),<br>        ];<br>    }<br>}</pre><p>Here, SimilaritySearch gives the agent the ability to search our document model using vector similarity.</p><p>The agent can decide when to search the knowledge base based on the user’s question.</p><h3>Step 9: Ask Questions Using Our Own Knowledge</h3><p>Now let’s create a route:</p><pre>use App\Ai\Agents\LaravelAssistant;<br>use Illuminate\Support\Facades\Route;</pre><pre>Route::get(&#39;/knowledge-ai&#39;, function () {</pre><pre>    $response = LaravelAssistant::make()<br>        -&gt;prompt(<br>            &#39;Can unused leave be transferred to the next year?&#39;<br>        );</pre><pre>    return response()-&gt;json([<br>        &#39;answer&#39; =&gt; $response-&gt;text,<br>    ]);<br>});</pre><p>Start the Laravel server:</p><pre>php artisan serve</pre><p>Open:</p><pre>http://127.0.0.1:8000/knowledge-ai</pre><p>Our AI agent can search the knowledge base, retrieve the relevant document, and generate an answer based on it.</p><p>An example response:</p><blockquote><em>According to the Annual Leave Policy, employees receive 12 paid leaves annually. Unused leave may be carried forward according to company policy.</em></blockquote><p>The exact response depends on the model and the documents retrieved.</p><h3>Step 10: How the Complete RAG Workflow Works</h3><pre>DOCUMENT INGESTION<br>                  |<br>                  v<br>         Company Documents<br>                  |<br>                  v<br>           Extract Text<br>                  |<br>                  v<br>          Generate Embeddings<br>                  |<br>                  v<br>          Store in Database<br>                  |<br>                  v<br>          VECTOR KNOWLEDGE BASE<br>                  |<br>                  |<br>           User Question<br>                  |<br>                  v<br>           Laravel AI Agent<br>                  |<br>                  v<br>          Similarity Search<br>                  |<br>                  v<br>       Retrieve Relevant Documents<br>                  |<br>                  v<br>        AI Generates Final Answer<br>                  |<br>                  v<br>             User Response</pre><h3>What Can We Build With RAG?</h3><p>RAG is useful for many real-world Laravel applications.</p><h3>HR Applications</h3><ul><li>Leave policy assistant</li><li>Employee handbook search</li><li>HR FAQs</li><li>Benefits information</li></ul><h3>SaaS Applications</h3><ul><li>Customer documentation assistant</li><li>Help-center search</li><li>Product FAQs</li><li>Tenant-specific knowledge base</li></ul><h3>Project Management Systems</h3><ul><li>Project documentation search</li><li>Process guidelines</li><li>Project summaries</li><li>Historical project knowledge</li></ul><h3>CRM &amp; ERP</h3><ul><li>Customer contract search</li><li>Quotation policies</li><li>Product documentation</li><li>Internal sales guidelines</li></ul><h3>Production Considerations</h3><p>The example above is intentionally simple. A production implementation should also consider:</p><ul><li>Splitting large documents into smaller chunks.</li><li>Processing uploads asynchronously with queues.</li><li>Storing source filenames and page numbers.</li><li>Filtering results by tenant and access permissions.</li><li>Updating or deleting embeddings when documents change.</li><li>Preventing unauthorized users from searching private documents.</li><li>Tracking AI usage and API costs.</li><li>Returning source references so users can verify answers.</li></ul><p>For multi-tenant SaaS applications, tenant isolation is especially important.</p><p>A user from Organization A must never retrieve documents belonging to Organization B. Make sure your similarity-search query enforces the appropriate authorization and tenant filters.</p><h3>Final Thoughts</h3><p>RAG is one of the most useful techniques for building AI-powered business applications.</p><p>It allows us to connect AI models with our own knowledge without retraining the model every time our documents change.</p><p>With Laravel AI SDK, we can generate embeddings, store vectors, perform semantic searches, and provide our AI agents with access to relevant information.</p><p>The result is an AI assistant that can answer questions using our application’s knowledge — not just general AI knowledge.</p><p>In the next article, we’ll take our AI application closer to production by exploring <strong>security, queues, human approval, and reliable AI workflows</strong>.</p><p>Because building an AI feature is exciting.</p><p>Building one that is secure, scalable, and reliable is what really matters.</p><h3>References</h3><ul><li><a href="https://laravel.com/docs/13.x/ai-sdk">Laravel AI SDK — Official Documentation</a></li><li><a href="https://laravel.com/docs/13.x/ai-sdk#embeddings">Laravel AI SDK — Embeddings</a></li><li><a href="https://laravel.com/docs/13.x/ai-sdk#similarity-search">Laravel AI SDK — Similarity Search</a></li><li><a href="https://laravel.com/blog/laravel-ai-integration-build-a-document-search-agent">Laravel AI Integration: Build a Document Search Agent</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbc96e2a377f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Give Your Laravel AI Agent Real Powers: Building Custom Tools]]></title>
            <link>https://medium.com/@devrekha/give-your-laravel-ai-agent-real-powers-building-custom-tools-8c584b4476a4?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c584b4476a4</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-11-23T08:01:02.785Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Laravel AI Series — Part 4</em></p><p>Learn how to connect AI agents with Laravel functions using custom tools, schemas, and PHP business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIM2MAHE_rcFwobk448yMw.jpeg" /></figure><p>In Part 3, we created our first dedicated AI Agent class in Laravel.</p><p>Our agent could understand instructions and answer questions. But there was still one important limitation: it couldn’t perform actions using our application’s functionality.</p><p>What if we want our AI agent to calculate project costs, retrieve information, check task status, or search our database?</p><p>This is where <strong>AI Agent Tools</strong> come in.</p><p>Tools allow an AI agent to use specific functions provided by our Laravel application. Instead of only generating text, the agent can request that our application execute a defined operation and use the result in its response.</p><p>Let’s understand this with a practical example.</p><h3>What are AI Agent Tools?</h3><p>Think of an AI agent as the brain, and tools as its hands.</p><p>The AI model understands the user’s request and decides whether it needs a tool. Laravel executes that tool, returns the result, and the AI uses the result to respond.</p><p>For example:</p><p><strong>User:</strong></p><blockquote><em>Calculate the project cost for 120 hours at ₹800 per hour.</em></blockquote><p>The agent recognizes that it needs a calculation tool.</p><p>The tool calculates:</p><pre>Total Hours: 120<br>Hourly Rate: ₹800<br>Total Cost: ₹96,000</pre><p>The agent then converts the result into a friendly response.</p><p>The AI doesn’t need to perform every operation itself. It can delegate specific tasks to our Laravel code.</p><h3>Step 1: Create a Tool</h3><p>Laravel AI SDK provides an Artisan command to create a tool.</p><p>Run:</p><pre>php artisan make:tool CalculateProjectCost</pre><p>Laravel will generate the tool class under:</p><pre>app/Ai/Tools/CalculateProjectCost.php</pre><p>A tool generally defines three important things:</p><ul><li>description() — explains when the AI should use this tool.</li><li>schema() — defines the parameters the AI can supply.</li><li>handle() — executes the actual PHP functionality.</li></ul><h3>Step 2: Implement the Tool</h3><p>Open CalculateProjectCost.php and add the following code:</p><pre>&lt;?php</pre><pre>namespace App\Ai\Tools;</pre><pre>use Illuminate\Contracts\JsonSchema\JsonSchema;<br>use Laravel\Ai\Contracts\Tool;<br>use Laravel\Ai\Tools\Request;<br>use Stringable;</pre><pre>class CalculateProjectCost implements Tool<br>{<br>    public function description(): Stringable|string<br>    {<br>        return &#39;Calculate the total project cost using<br>                allocated hours and hourly rate.&#39;;<br>    }</pre><pre>    public function schema(JsonSchema $schema): array<br>    {<br>        return [<br>            &#39;hours&#39; =&gt; $schema-&gt;integer()<br>                -&gt;min(1)<br>                -&gt;required(),</pre><pre>            &#39;hourly_rate&#39; =&gt; $schema-&gt;integer()<br>                -&gt;min(0)<br>                -&gt;required(),<br>        ];<br>    }</pre><pre>    public function handle(Request $request): Stringable|string<br>    {<br>        $hours = $request[&#39;hours&#39;];<br>        $hourlyRate = $request[&#39;hourly_rate&#39;];</pre><pre>        $totalCost = $hours * $hourlyRate;</pre><pre>        return &quot;Project hours: {$hours}. &quot;<br>            . &quot;Hourly rate: {$hourlyRate}. &quot;<br>            . &quot;Total estimated cost: {$totalCost}.&quot;;<br>    }<br>}</pre><p>Let’s understand this code.</p><h3>description()</h3><p>The description tells the AI model what this tool is designed to do.</p><p>A clear description helps the model understand when it should call the tool.</p><h3>schema()</h3><p>The schema defines the input parameters required by our tool.</p><p>In this example, we require:</p><ul><li>hours — total project hours</li><li>hourly_rate — cost per hour</li></ul><p>The AI model can use the schema to provide correctly structured tool arguments.</p><h3>handle()</h3><p>This method contains the actual business logic.</p><p>The AI does not execute the calculation directly inside Laravel. It requests the tool, and our PHP code performs the calculation.</p><p>This distinction is important because we control the functionality that gets executed.</p><h3>Step 3: Connect the Tool to Our AI Agent</h3><p>Creating a tool is not enough. We must tell our agent that the tool is available.</p><p>Open the LaravelAssistant agent we created in Part 3.</p><p>Add the tool to the agent’s tools() method:</p><pre>&lt;?php</pre><pre>namespace App\Ai\Agents;</pre><pre>use App\Ai\Tools\CalculateProjectCost;<br>use Laravel\Ai\Contracts\Agent;<br>use Laravel\Ai\Promptable;</pre><pre>class LaravelAssistant implements Agent<br>{<br>    use Promptable;</pre><pre>    public function instructions(): string<br>    {<br>        return &#39;You are a helpful Laravel developer<br>                and project management assistant.</pre><pre>                Use the CalculateProjectCost tool<br>                whenever the user asks to calculate<br>                project costs using hours and hourly rates.</pre><pre>                Explain calculations clearly.&#39;;<br>    }</pre><pre>    public function tools(): iterable<br>    {<br>        return [<br>            new CalculateProjectCost,<br>        ];<br>    }<br>}</pre><p>Now our agent knows that it has access to the CalculateProjectCost tool.</p><p>When the user asks a question that requires project cost calculation, the model can decide to use it.</p><h3>Step 4: Send a Request to the Agent</h3><p>Let’s call our agent from a Laravel route.</p><pre>use App\Ai\Agents\LaravelAssistant;<br>use Illuminate\Support\Facades\Route;</pre><pre>Route::get(&#39;/project-cost-ai&#39;, function () {</pre><pre>    $response = LaravelAssistant::make()<br>        -&gt;prompt(<br>            &#39;Calculate project cost for 120 hours<br>             at an hourly rate of 800.&#39;<br>        );</pre><pre>    return response()-&gt;json([<br>        &#39;response&#39; =&gt; $response-&gt;text,<br>    ]);<br>});</pre><p>Run your application:</p><pre>php artisan serve</pre><p>Open:</p><pre>http://127.0.0.1:8000/project-cost-ai</pre><p>The AI agent can recognize that it needs a calculation, call our tool, receive the result, and formulate a response.</p><p>An example response could be:</p><blockquote><em>The estimated project cost is ₹96,000. This is calculated using 120 project hours at ₹800 per hour.</em></blockquote><p>The wording may vary depending on the AI model.</p><h3>Step 5: Understand the Tool Workflow</h3><p>Here is what happens behind the scenes:</p><pre>User Request<br>     |<br>     v<br>Laravel AI Agent<br>     |<br>     v<br>AI Understands the Request<br>     |<br>     v<br>AI Selects CalculateProjectCost<br>     |<br>     v<br>Laravel Executes handle()<br>     |<br>     v<br>Calculation Result Returned<br>     |<br>     v<br>AI Generates Final Response</pre><p>The important point is that the model decides when to use the tool based on the request and tool description, while Laravel executes the actual PHP code.</p><p>This gives us a powerful combination:</p><p><strong>AI reasoning + Laravel business logic</strong></p><h3>Step 6: What Else Can We Build With Tools?</h3><p>The calculator is just a simple example.</p><p>In real applications, we can create tools for:</p><h3>Project Management</h3><ul><li>Retrieve project details</li><li>Find overdue tasks</li><li>Calculate allocated hours</li><li>Check project progress</li><li>Summarize workload</li></ul><h3>CRM</h3><ul><li>Search customers</li><li>Retrieve lead information</li><li>Check follow-up history</li><li>Summarize customer interactions</li></ul><h3>Quotation &amp; ERP</h3><ul><li>Search quotations</li><li>Retrieve quotation status</li><li>Calculate quotation totals</li><li>Summarize historical orders</li></ul><h3>SaaS Applications</h3><ul><li>Retrieve tenant-specific data</li><li>Check subscription information</li><li>Analyze usage</li><li>Generate reports</li></ul><p>Every tool should have a clear responsibility and limited access.</p><p>For example, instead of giving an AI agent unrestricted database access, we can provide a SearchCustomer tool that retrieves only authorized customer information.</p><p>This is much easier to control, test, and maintain.</p><h3>Important: Security Comes First</h3><p>AI tools can execute application functionality, so security should never be ignored.</p><p>Before building production tools:</p><ul><li>Validate every input.</li><li>Apply authorization checks.</li><li>Restrict data to the authenticated user or tenant.</li><li>Avoid exposing sensitive database fields.</li><li>Use read-only tools when possible.</li><li>Require human approval for sensitive actions.</li><li>Log important tool calls.</li><li>Never allow AI-generated arguments to bypass application rules.</li></ul><p>AI should not be trusted with unrestricted access to your database or application.</p><p>Tools should expose only the functionality your AI agent genuinely needs.</p><h3>Final Thoughts</h3><p>AI Agent Tools are one of the most useful features when building real-world AI applications with Laravel.</p><p>They allow us to connect AI reasoning with our existing PHP business logic.</p><p>Instead of building a chatbot that only answers questions, we can build an assistant that retrieves information, performs calculations, checks data, and works with our application in a controlled way.</p><p>The key is to keep the AI responsible for understanding and deciding when to use a tool, while Laravel remains responsible for executing the actual business logic.</p><p>In the next article, we’ll explore how to connect AI agents to our own data using <strong>RAG (Retrieval-Augmented Generation)</strong>, allowing them to answer questions using company documents and application knowledge.</p><h3>References</h3><ul><li><a href="https://laravel.com/docs/13.x/ai-sdk">Laravel AI SDK — Official Documentation</a></li><li><a href="https://laravel.com/blog/laravel-ai-sdk-building-production-safe-database-tools-for-agents">Laravel AI SDK — Building Production-Safe Database Tools</a></li><li><a href="https://github.com/laravel/ai">Laravel AI SDK — GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c584b4476a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Your First AI Agent in Laravel: From Anonymous Prompt to Reusable Agent]]></title>
            <link>https://medium.com/@devrekha/create-your-first-ai-agent-in-laravel-from-anonymous-prompt-to-reusable-agent-1302fefb9370?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1302fefb9370</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 08:01:03 GMT</pubDate>
            <atom:updated>2026-11-22T08:01:03.727Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Laravel AI Series — Part 3</em></p><p>Learn to create a dedicated Laravel AI Agent class with reusable instructions and clean architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCV5sHe1V-C5KUAkml_NEg.jpeg" /></figure><p>In Part 2, we installed Laravel AI SDK and made our first AI request using an anonymous agent.</p><p>It was simple — and that’s exactly what we wanted for our first experiment.</p><p>But imagine building a real application with multiple AI features.</p><p>One agent analyzes projects. Another summarizes documents. Another assists customers. Another generates reports.</p><p>Would you put all your prompts inside controllers and routes?</p><p>Probably not.</p><p>In this article, we’ll take the next step and create a dedicated AI Agent class in Laravel.</p><h3>Why do we need dedicated agents?</h3><p>An anonymous agent is useful for quick experiments and one-time requests.</p><p>But when AI functionality becomes part of our application, we need:</p><ul><li>Reusable AI logic</li><li>Clear instructions</li><li>Separation of responsibilities</li><li>Easier maintenance</li><li>Better testing</li><li>A structure that can grow with our application</li></ul><p>Instead of keeping AI logic inside controllers, Laravel allows us to organize it into dedicated agent classes.</p><p>Let’s build one.</p><h3>Step 1: Create an Agent</h3><p>Laravel AI SDK provides an Artisan command to generate an agent class.</p><p>Run:</p><pre>php artisan make:agent LaravelAssistant</pre><p>Laravel will generate an agent class under:</p><pre>app/Ai/Agents/LaravelAssistant.php</pre><p>This is where we define the behavior of our AI assistant.</p><h3>Step 2: Define the Agent Instructions</h3><p>Open the generated LaravelAssistant.php file.</p><p>Let’s define a simple Laravel developer assistant:</p><pre>&lt;?php</pre><pre>namespace App\Ai\Agents;</pre><pre>use Laravel\Ai\Contracts\Agent;<br>use Laravel\Ai\Promptable;</pre><pre>class LaravelAssistant implements Agent<br>{<br>    use Promptable;</pre><pre>    public function instructions(): string<br>    {<br>        return &#39;You are an experienced Laravel developer.<br>                Explain Laravel concepts clearly.<br>                Provide practical examples when appropriate.<br>                Keep answers beginner-friendly.&#39;;<br>    }<br>}</pre><p>Let’s understand the important parts.</p><p><strong>Agent interface</strong></p><p>This identifies the class as an AI agent within Laravel AI SDK.</p><p><strong>Promptable trait</strong></p><p>This provides the functionality needed to send prompts to the AI model.</p><p><strong>instructions() method</strong></p><p>This defines the agent’s role, behavior, and response style.</p><p>Instead of repeating instructions with every request, we define them once in our agent class.</p><h3>Step 3: Use the Agent</h3><p>Now let’s use our newly created agent.</p><p>Add a route in routes/web.php:</p><pre>use App\Ai\Agents\LaravelAssistant;<br>use Illuminate\Support\Facades\Route;</pre><pre>Route::get(&#39;/laravel-assistant&#39;, function () {</pre><pre>    $response = LaravelAssistant::make()<br>        -&gt;prompt(&#39;What is Laravel middleware?&#39;);</pre><pre>    return response()-&gt;json([<br>        &#39;question&#39; =&gt; &#39;What is Laravel middleware?&#39;,<br>        &#39;answer&#39; =&gt; $response-&gt;text,<br>    ]);<br>});</pre><p>Notice that we are no longer writing the agent instructions inside the route.</p><p>Our route simply calls the agent and passes the question.</p><h3>Step 4: Test the Agent</h3><p>Start your Laravel application:</p><pre>php artisan serve</pre><p>Open:</p><pre>http://127.0.0.1:8000/laravel-assistant</pre><p>You should receive a JSON response containing an explanation of Laravel middleware.</p><p>The response will be generated by the AI model using the instructions we defined in our agent.</p><p>Try changing the prompt:</p><pre>-&gt;prompt(&#39;Explain Laravel service providers with an example.&#39;)</pre><p>Or:</p><pre>-&gt;prompt(&#39;What is the difference between Laravel events and listeners?&#39;)</pre><p>Our agent can answer different questions while maintaining the same role and instructions.</p><h3>Step 5: Reuse the Agent Anywhere</h3><p>The real advantage of a dedicated agent is reusability.</p><p>You can call LaravelAssistant from:</p><ul><li>Controllers</li><li>Jobs</li><li>Artisan commands</li><li>Livewire components</li><li>Scheduled tasks</li><li>Other application services</li></ul><p>For example, inside a controller:</p><pre>$response = LaravelAssistant::make()<br>    -&gt;prompt($request-&gt;input(&#39;question&#39;));</pre><pre>return $response-&gt;text;</pre><p>You don’t need to redefine the instructions every time.</p><p>The agent owns its behavior, and your application simply interacts with it.</p><h3>Anonymous Agent vs Dedicated Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*TOaoz58ixlPRVARZ-pzgqQ.png" /></figure><p>Both approaches have their place.</p><p>For a quick experiment, anonymous agents are great.</p><p>For a feature that belongs to your application, dedicated agents are usually a better architectural choice.</p><h3>What’s Next?</h3><p>We have created our first reusable AI Agent.</p><p>But currently, our agent can only answer questions using its model knowledge and the context we provide.</p><p>What if we want it to retrieve actual project information from our database?</p><p>What if it needs to check overdue tasks, retrieve customer details, or search quotations?</p><p>In <strong>Part 4</strong>, we’ll explore AI Agent Tools and give our Laravel agent the ability to interact with specific application functionality.</p><p>That’s when our AI assistant starts becoming more than just a chatbot.</p><h3>References</h3><ul><li><a href="https://laravel.com/docs/13.x/ai-sdk">Laravel AI SDK — Official Documentation</a></li><li><a href="https://laravel.com/blog/building-ai-agents-with-laravel-no-python-required">Building AI Agents with Laravel: No Python Required</a></li><li><a href="https://github.com/laravel/ai">Laravel AI SDK — GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1302fefb9370" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Laravel AI SDK: Installation & Your First AI Request]]></title>
            <link>https://medium.com/@devrekha/getting-started-with-laravel-ai-sdk-installation-your-first-ai-request-e1268197a286?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1268197a286</guid>
            <category><![CDATA[laravel-developer]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 08:01:03 GMT</pubDate>
            <atom:updated>2026-11-21T08:01:03.725Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Laravel AI Series — Part 2</em></p><p>A step-by-step guide to installing Laravel AI SDK, configuring your provider, and making your first AI request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFjh_zaIbdxfLCqlqqJSVA.jpeg" /></figure><p>In the previous article, we discussed how AI is changing Laravel development and how we can build smarter applications using AI agents.</p><p>Now, let’s stop talking about AI and start building.</p><p>In this article, we’ll install Laravel’s AI SDK, configure an AI provider, and send our first prompt from a Laravel application.</p><p>Our goal is simple: <strong>make our Laravel application communicate with an AI model.</strong></p><h3>Step 1: Check your Laravel environment</h3><p>For this tutorial, we’ll use a Laravel application with a compatible PHP version.</p><p>Laravel 13 requires PHP 8.3 or newer.</p><p>If you already have a Laravel project, you can continue with it. Otherwise, create a new project:</p><pre>composer create-project laravel/laravel laravel-ai-demo</pre><pre>cd laravel-ai-demo</pre><p>Check your installed versions:</p><pre>php -v</pre><pre>php artisan --version</pre><h3>Step 2: Install Laravel AI SDK</h3><p>Laravel provides an official AI SDK that allows us to interact with supported AI providers through a Laravel-friendly API.</p><p>Install it using Composer:</p><pre>composer require laravel/ai</pre><p>That’s it. Composer will install the package and its dependencies.</p><h3>Step 3: Publish the configuration</h3><p>Next, publish the AI SDK configuration and migration files:</p><pre>php artisan vendor:publish --provider=&quot;Laravel\Ai\AiServiceProvider&quot;</pre><p>This will publish the AI configuration file, allowing us to configure providers and default models.</p><h3>Step 4: Run the migrations</h3><p>The SDK includes database tables used for storing agent conversations and messages.</p><p>Run:</p><pre>php artisan migrate</pre><p>This creates the SDK’s conversation storage tables along with any pending migrations in your application.</p><h3>Step 5: Configure your AI provider</h3><p>For this tutorial, we’ll use OpenAI as an example provider.</p><p>You need an API key from your selected AI provider. Keep your key private and never commit it to Git.</p><p>Add your API key to the .env file:</p><pre>OPENAI_API_KEY=your_api_key_here</pre><p>Replace your_api_key_here with your actual API key.</p><blockquote><em>Never expose your AI API key in frontend JavaScript, public repositories, or browser requests. Keep it on your Laravel backend.</em></blockquote><p>Laravel AI SDK supports multiple providers. You can use the provider you prefer, depending on the models and capabilities available to your account.</p><h3>Step 6: Make your first AI request</h3><p>Now comes the exciting part!</p><p>We can use an anonymous agent for a quick AI request without creating a separate agent class.</p><p>Open routes/web.php and add:</p><pre>use function Laravel\Ai\agent;</pre><pre>Route::get(&#39;/ai-test&#39;, function () {</pre><pre>    $response = agent(<br>        instructions: &#39;You are a helpful Laravel developer assistant.&#39;,<br>    )-&gt;prompt(&#39;Explain Laravel service providers in simple words.&#39;);</pre><pre>    return response()-&gt;json([<br>        &#39;response&#39; =&gt; $response-&gt;text,<br>    ]);<br>});</pre><p>Here is what is happening:</p><ul><li>agent() creates an anonymous AI agent.</li><li>instructions define how the AI should behave.</li><li>prompt() sends our question to the model.</li><li>$response-&gt;text contains the generated response.</li></ul><p>We haven’t created a dedicated agent class yet. This is a quick way to experiment and understand the SDK.</p><h3>Step 7: Test your first AI integration</h3><p>Start your Laravel development server:</p><pre>php artisan serve</pre><p>Open the following URL in your browser:</p><pre>http://127.0.0.1:8000/ai-test</pre><p>If your API key and provider configuration are correct, Laravel should return a JSON response containing the AI-generated explanation.</p><p>For example:</p><pre>{<br>    &quot;response&quot;: &quot;Laravel service providers are classes that...&quot;<br>}</pre><p>The actual response will be generated by your configured AI model.</p><p>Congratulations! Your Laravel application has successfully made its first AI request.</p><h3>What did we build?</h3><p>In just a few steps, we:</p><ul><li>Installed the Laravel AI SDK.</li><li>Published its configuration.</li><li>Ran the required migrations.</li><li>Configured an AI provider.</li><li>Created an anonymous agent.</li><li>Sent a prompt to an AI model.</li><li>Received the generated response.</li></ul><p>This is the foundation for building much more powerful AI features.</p><h3>What’s next?</h3><p>In this article, we used an anonymous agent for a simple AI request.</p><p>But in real applications, we don’t want to keep writing prompts inside routes or controllers.</p><p>We need reusable AI components with their own instructions, responsibilities, and configuration.</p><p>In <strong>Part 3</strong>, we’ll create our first dedicated Laravel AI Agent class, organize the code properly, and build a reusable assistant instead of using an anonymous agent.</p><p>Let’s take the next step toward building real AI-powered Laravel applications.</p><h3>References</h3><ul><li><a href="https://laravel.com/docs/13.x/ai-sdk">Laravel AI SDK Official Documentation</a></li><li><a href="https://laravel.com/blog/introducing-laravel-ai-sdk-v1">Introducing Laravel AI SDK v1.0</a></li><li><a href="https://github.com/laravel/ai">Laravel AI SDK on GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1268197a286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel + AI: A New Era for PHP Developers]]></title>
            <link>https://medium.com/@devrekha/laravel-ai-a-new-era-for-php-developers-c1a93aed8e7b?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1a93aed8e7b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 05:52:46 GMT</pubDate>
            <atom:updated>2026-11-20T07:00:49.734Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Laravel AI Series — Part 1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GqPRRU7QfKIOQJfkY8VLg.jpeg" /></figure><p><em>AI is no longer just a chatbot. It is becoming part of the applications we build — and Laravel developers are ready for it.</em></p><p>For the past few years, AI has been changing the way we develop software.</p><p>We have seen AI chatbots, code assistants, automated content generation, smart search, and applications that can analyze data and make recommendations.</p><p>But one question remained for many PHP developers:</p><p><strong>Can we build powerful AI applications using Laravel without creating a separate Python backend?</strong></p><p>The answer is now yes.</p><p>Laravel’s AI SDK brings AI capabilities directly into the Laravel ecosystem. Developers can build AI agents, connect tools, maintain conversations, generate structured responses, stream content, and work with their own data.</p><p>Instead of treating AI as an external feature, we can integrate it into our existing Laravel applications using familiar development patterns.</p><p>Imagine a project management application where AI can analyze overdue tasks.</p><p>A quotation system where AI can summarize customer history.</p><p>A CRM where AI can classify leads and suggest follow-ups.</p><p>Or a SaaS application where users can ask questions about their own business data.</p><p>These are not just chatbot features. They are practical ways to make applications smarter and more useful.</p><p>The Laravel AI SDK gives us a foundation to explore these possibilities using PHP.</p><p>But before building something complex, we should understand the basics.</p><p>In this series, we’ll explore Laravel AI step by step — from installation and our first AI agent to tools, RAG, and production-ready AI workflows.</p><p>No complicated theory. Just Laravel, AI, and practical development.</p><h3>What’s coming next?</h3><p>In the next article, we’ll install the Laravel AI SDK, configure our AI provider, and make our first AI request from a Laravel application.</p><p>Let’s start building.</p><p><strong>References</strong></p><ul><li><a href="https://laravel.com/docs/13.x/ai-sdk">Laravel AI SDK Documentation</a></li><li><a href="https://laravel.com/blog/introducing-laravel-ai-sdk-v1">Introducing Laravel AI SDK v1.0</a></li><li><a href="https://laravel.com/blog/building-ai-agents-with-laravel-no-python-required">Building AI Agents with Laravel: No Python Required</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1a93aed8e7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Service Container vs Service Provider: The Difference Every Developer Should Know]]></title>
            <link>https://medium.com/@devrekha/laravel-service-container-vs-service-provider-the-difference-every-developer-should-know-06c995feeb3c?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/06c995feeb3c</guid>
            <category><![CDATA[laravel-service-provider]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[laravel-service-container]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-07-03T08:01:02.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25Rb_n5XGvRXkyDLbJRDHg.png" /></figure><p>If you’ve been working with Laravel for some time, you’ve probably encountered both <strong>Service Containers</strong> and <strong>Service Providers</strong>. Many developers confuse these concepts because they often work together.</p><p>The simplest way to understand them is:</p><blockquote><strong><em>Service Providers tell Laravel WHAT services exist.</em></strong></blockquote><blockquote><strong><em>The Service Container decides HOW those services are created and resolved.</em></strong></blockquote><p>Understanding this distinction will help you write cleaner, more maintainable, and scalable Laravel applications.</p><h3>What is Laravel Service Container?</h3><p>The Service Container is Laravel’s dependency injection container.</p><p>It is responsible for:</p><ul><li>Managing class dependencies</li><li>Resolving objects automatically</li><li>Handling singleton instances</li><li>Injecting dependencies into controllers, services, jobs, and commands</li></ul><h3>Example</h3><pre>class PaymentGateway<br>{<br>    public function process()<br>    {<br>        return &#39;Payment Processed&#39;;<br>    }<br>}</pre><p>Laravel can automatically resolve it:</p><pre>class OrderController extends Controller<br>{<br>    public function store(PaymentGateway $gateway)<br>    {<br>        return $gateway-&gt;process();<br>    }<br>}</pre><p>No manual instantiation is required.</p><p>Laravel’s Service Container creates the object and injects it automatically.</p><h3>What is a Service Provider?</h3><p>Service Providers are the central place where Laravel bootstraps services.</p><p>They are used to:</p><ul><li>Register bindings</li><li>Register singletons</li><li>Load routes</li><li>Load events</li><li>Load listeners</li><li>Load package resources</li></ul><h3>Example</h3><pre>class PaymentServiceProvider extends ServiceProvider<br>{<br>    public function register()<br>    {<br>        $this-&gt;app-&gt;bind(<br>            PaymentGatewayInterface::class,<br>            StripePaymentGateway::class<br>        );<br>    }<br>}</pre><p>This tells Laravel:</p><blockquote><em>Whenever someone requests </em><em>PaymentGatewayInterface, provide </em><em>StripePaymentGateway.</em></blockquote><h3>How They Work Together</h3><p>Consider the application startup process:</p><h3>Step 1</h3><p>Laravel starts.</p><h3>Step 2</h3><p>Service Providers are loaded.</p><pre>$this-&gt;app-&gt;bind(<br>    PaymentGatewayInterface::class,<br>    StripePaymentGateway::class<br>);</pre><h3>Step 3</h3><p>The Service Container stores these bindings.</p><h3>Step 4</h3><p>A controller requests a dependency.</p><pre>public function store(<br>    PaymentGatewayInterface $gateway<br>)</pre><h3>Step 5</h3><p>The Service Container resolves the dependency and injects it.</p><h3>Real-World Example</h3><p>Imagine you’re building a SaaS application that supports multiple payment gateways.</p><h3>Interface</h3><pre>interface PaymentGatewayInterface<br>{<br>    public function pay($amount);<br>}</pre><h3>Stripe Implementation</h3><pre>class StripeGateway implements PaymentGatewayInterface<br>{<br>    public function pay($amount)<br>    {<br>        return &quot;Paid using Stripe&quot;;<br>    }<br>}</pre><h3>Provider Registration</h3><pre>public function register()<br>{<br>    $this-&gt;app-&gt;singleton(<br>        PaymentGatewayInterface::class,<br>        StripeGateway::class<br>    );<br>}</pre><h3>Usage</h3><pre>public function checkout(<br>    PaymentGatewayInterface $gateway<br>)<br>{<br>    return $gateway-&gt;pay(100);<br>}</pre><p>The controller never knows which implementation is being used.</p><p>This makes the application easier to maintain and test.</p><h3>Common Mistakes</h3><h3>Mistake #1: Using Service Providers for Business Logic</h3><p>Bad:</p><pre>public function boot()<br>{<br>    // Business logic here<br>}</pre><p>Service Providers should only configure the application.</p><h3>Mistake #2: Binding Everything</h3><p>Not every class needs manual registration.</p><p>Laravel can automatically resolve many classes.</p><h3>Mistake #3: Confusing Registration with Resolution</h3><p>Developers often think:</p><pre>$this-&gt;app-&gt;bind(...)</pre><p>creates an object.</p><p>It doesn’t.</p><p>It only registers instructions.</p><p>The actual object is created later by the Service Container.</p><h3>Service Container vs Service Provider</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*cGlpkxxUQELk9TqrBc1R9Q.png" /></figure><h3>Final Thoughts</h3><p>A simple rule to remember:</p><blockquote><strong><em>Service Providers register services.</em></strong></blockquote><blockquote><strong><em>Service Container resolves services.</em></strong></blockquote><p>Whenever Laravel injects a dependency into a controller, service, command, event, or job, the Service Container is doing the work. Service Providers simply tell Laravel what should be available in the container.</p><p>Understanding this relationship is one of the most important steps toward mastering Laravel’s architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06c995feeb3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Structure Large Laravel Projects: A Clean, Scalable Architecture Guide]]></title>
            <link>https://medium.com/@devrekha/how-i-structure-large-laravel-projects-a-clean-scalable-architecture-guide-195a232f443a?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/195a232f443a</guid>
            <category><![CDATA[policy]]></category>
            <category><![CDATA[large-laravel-projects]]></category>
            <category><![CDATA[repository-service]]></category>
            <category><![CDATA[scalable-architecture]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 09:20:09 GMT</pubDate>
            <atom:updated>2026-06-29T09:20:09.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4QLETY4mAcEREAlIUIdxg.png" /></figure><p>As Laravel applications grow, maintaining clean code becomes increasingly challenging. Controllers become bloated, business logic gets scattered, and introducing new features often creates unexpected side effects.</p><p>Over the years, I’ve found that large Laravel projects remain maintainable when the architecture focuses on <strong>separation of concerns</strong>, <strong>modularity</strong>, and <strong>predictability</strong>. Here’s the structure I follow for enterprise-level Laravel applications.</p><h3>1. Keep Controllers Thin</h3><p>Controllers should only handle:</p><ul><li>Request validation</li><li>Calling services</li><li>Returning responses</li></ul><h3>❌ Bad Example</h3><pre>public function store(Request $request)<br>{<br>    $validated = $request-&gt;validate([<br>        &#39;name&#39; =&gt; &#39;required&#39;,<br>        &#39;email&#39; =&gt; &#39;required|email&#39;,<br>    ]);<br><br>    $user = User::create($validated);<br><br>    Mail::to($user-&gt;email)-&gt;send(new WelcomeMail($user));<br><br>    return response()-&gt;json($user);<br>}</pre><p>The controller is handling:</p><ul><li>Validation</li><li>Database operations</li><li>Email sending</li></ul><h3>✅ Better Example</h3><pre>public function store(CreateUserRequest $request)<br>{<br>    $user = $this-&gt;userService-&gt;createUser(<br>        $request-&gt;validated()<br>    );<br><br>    return response()-&gt;json($user);<br>}</pre><p>Controllers remain small and easy to read.</p><h3>2. Move Business Logic to Service Classes</h3><p>Business rules should live inside dedicated services.</p><h3>Example Structure</h3><pre>app/<br>└── Services/<br>    └── OrderService.php</pre><h3>Example Service</h3><pre>class OrderService<br>{<br>    public function create(array $data)<br>    {<br>        $order = Order::create($data);<br><br>        $this-&gt;reserveStock($order);<br><br>        $this-&gt;sendNotifications($order);<br><br>        return $order;<br>    }<br>}</pre><h3>Benefits</h3><ul><li>Reusable</li><li>Testable</li><li>Easier maintenance</li><li>Clear separation from HTTP layer</li></ul><h3>3. Organize by Feature, Not Just Layer</h3><p>Many Laravel projects become difficult to navigate because everything is grouped by type.</p><h3>Traditional Structure</h3><pre>app/<br>├── Http/Controllers<br>├── Models<br>├── Services</pre><h3>Feature-Based Structure</h3><pre>app/<br>├── Modules/<br>│   ├── Auth/<br>│   │   ├── Controllers<br>│   │   ├── Requests<br>│   │   ├── Services<br>│   │   └── Models<br>│   ├── Orders/<br>│   ├── Payments/<br>│   └── Users/</pre><p>This structure:</p><ul><li>Improves discoverability</li><li>Makes ownership clearer</li><li>Scales better for larger teams</li></ul><h3>4. Use Repositories Carefully</h3><p>Repositories are useful when you need an abstraction layer between your business logic and data source.</p><h3>Repository Interface</h3><pre>interface OrderRepository<br>{<br>    public function find(int $id);<br><br>    public function store(array $data);<br>}</pre><h3>Implementation</h3><pre>class EloquentOrderRepository implements OrderRepository<br>{<br>    public function find(int $id)<br>    {<br>        return Order::findOrFail($id);<br>    }<br><br>    public function store(array $data)<br>    {<br>        return Order::create($data);<br>    }<br>}</pre><h3>When to Use Repositories</h3><p>✅ Multiple data sources</p><p>✅ Complex query logic</p><p>✅ Easier testing and mocking</p><h3>When Not to Use Them</h3><p>❌ Simple CRUD applications</p><p>❌ Wrapping Eloquent methods without adding value</p><h3>5. Separate Responsibilities Clearly</h3><p>Each layer should have one responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*nMp8UiVi4aZLpVzHUiJpeQ.png" /></figure><h3>Example Flow</h3><pre>Request<br>   ↓<br>Controller<br>   ↓<br>Service<br>   ↓<br>Repository<br>   ↓<br>Database</pre><h3>6. Use Policies and Gates for Authorization</h3><p>Authorization should not live inside controllers.</p><h3>Policy Example</h3><pre>class OrderPolicy<br>{<br>    public function update(User $user, Order $order)<br>    {<br>        return $user-&gt;id === $order-&gt;user_id;<br>    }<br>}</pre><h3>Controller</h3><pre>public function update(Order $order)<br>{<br>    $this-&gt;authorize(&#39;update&#39;, $order);<br><br>    //<br>}</pre><p>Benefits:</p><ul><li>Reusable permissions</li><li>Centralized security</li><li>Cleaner controllers</li></ul><h3>7. Optimize for Readability First</h3><p>Developers spend more time reading code than writing it.</p><h3>Recommended Practices</h3><ul><li>Use meaningful class names</li><li>Keep methods short</li><li>Avoid deeply nested conditions</li><li>Extract reusable logic</li><li>Follow PSR standards</li></ul><h3>Example</h3><p>Instead of:</p><pre>if ($user &amp;&amp; $user-&gt;status == 1 &amp;&amp; $user-&gt;role == &#39;admin&#39;) {<br>    // ...<br>}</pre><p>Prefer:</p><pre>if ($user-&gt;isActiveAdmin()) {<br>    // ...<br>}</pre><h3>Suggested Enterprise Laravel Structure</h3><pre>app/<br>├── Modules/<br>│   ├── Auth/<br>│   ├── Orders/<br>│   ├── Payments/<br>│   └── Users/<br>│<br>├── Services/<br>├── Repositories/<br>├── Jobs/<br>├── Events/<br>├── Policies/<br>├── Traits/<br>├── Helpers/<br>└── Console/</pre><h3>Biggest Lesson Learned</h3><p>Large Laravel projects are easier to scale when the architecture remains:</p><ul><li>Simple</li><li>Modular</li><li>Predictable</li></ul><p>The goal isn’t to create more folders or layers. The goal is to ensure every piece of the application has a clear responsibility.</p><p>When controllers stay thin, services handle business logic, and responsibilities are properly separated, Laravel applications become significantly easier to understand, extend, test, and maintain.</p><h3>Final Thoughts</h3><p>A well-structured Laravel application isn’t about following a rigid pattern — it’s about creating a codebase that your future self and your team can confidently work with. Start simple, introduce abstractions only when they solve a real problem, and always prioritize clarity over cleverness.</p><p><strong>What architecture pattern do you follow in your Laravel projects? Share your experience in the comments.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195a232f443a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CORS in Laravel: Why It Happens and How to Fix It Properly]]></title>
            <link>https://medium.com/@devrekha/understanding-cors-in-laravel-why-it-happens-and-how-to-fix-it-properly-a2bb24908cd0?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2bb24908cd0</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[cors]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-06-19T08:01:02.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMoah1IjtRLsSjcdrZxQsw.png" /></figure><h3>Introduction</h3><p>If you’ve ever connected a React, Vue, Angular, Flutter, or mobile application to a Laravel API, you’ve probably seen an error like:</p><pre>Access to fetch at &#39;http://localhost:8000/api/users&#39;<br>from origin &#39;http://localhost:3000&#39;<br>has been blocked by CORS policy</pre><p>Most developers immediately think:</p><blockquote><em>“My API is broken.”</em></blockquote><p>But the truth is:</p><p><strong>Your Laravel API is usually working perfectly. The browser is blocking the request before your frontend can access the response.</strong></p><h3>What is CORS?</h3><p>CORS stands for:</p><p><strong>Cross-Origin Resource Sharing</strong></p><p>It is a browser security mechanism that controls whether one website can access resources from another website.</p><p>Consider:</p><pre>Frontend:<br>http://localhost:3000</pre><pre>Backend:<br>http://localhost:8000</pre><p>Although both run on localhost, they have different ports.</p><p>The browser treats them as different origins and applies CORS rules.</p><h3>What Defines an Origin?</h3><p>An origin consists of:</p><pre>Protocol + Domain + Port</pre><p>Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*qW8rXeWtmIjMwvlFqif-uQ.png" /></figure><p>Even a different port makes it a different origin.</p><h3>Why Browsers Block Requests</h3><p>Imagine you’re logged into your banking website.</p><p>A malicious website could silently make requests using your active session.</p><p>Without CORS protection, attackers could steal sensitive information.</p><p>CORS prevents unauthorized websites from reading responses from another origin.</p><h3>Common Laravel CORS Errors</h3><h3>Error 1</h3><pre>No &#39;Access-Control-Allow-Origin&#39; header is present</pre><h3>Error 2</h3><pre>Response to preflight request doesn&#39;t pass access control check</pre><h3>Error 3</h3><pre>Blocked by CORS policy</pre><p>These indicate the browser didn’t receive the required CORS headers from Laravel.</p><h3>How CORS Actually Works</h3><h3>Step 1: Browser Sends Request</h3><pre>React App<br>    |<br>    | GET /api/users<br>    |<br>Laravel API</pre><h3>Step 2: Browser Checks Response Headers</h3><p>Laravel must respond with:</p><pre>Access-Control-Allow-Origin: http://localhost:3000</pre><p>If missing:</p><pre>Request Blocked</pre><h3>Understanding Preflight Requests</h3><p>For POST, PUT, PATCH, DELETE requests, browsers often send an additional request:</p><pre>OPTIONS /api/users</pre><p>This is called a:</p><p><strong>Preflight Request</strong></p><p>The browser asks:</p><blockquote><em>“Laravel, are you okay with requests from this origin?”</em></blockquote><p>Only after approval does the actual request proceed.</p><h3>Laravel CORS Configuration</h3><p>Laravel provides built-in CORS support.</p><p>Open:</p><pre>config/cors.php</pre><p>Example:</p><pre>return [<br><br>    &#39;paths&#39; =&gt; [&#39;api/*&#39;],<br><br>    &#39;allowed_methods&#39; =&gt; [&#39;*&#39;],<br><br>    &#39;allowed_origins&#39; =&gt; [<br>        &#39;http://localhost:3000&#39;<br>    ],<br><br>    &#39;allowed_headers&#39; =&gt; [&#39;*&#39;],<br><br>    &#39;supports_credentials&#39; =&gt; true,<br><br>];</pre><h3>If Using Sanctum</h3><p>When using Laravel Sanctum:</p><pre>SESSION_DOMAIN=localhost</pre><pre>SANCTUM_STATEFUL_DOMAINS=localhost:3000</pre><p>Also ensure:</p><pre>&#39;supports_credentials&#39; =&gt; true</pre><p>Otherwise authentication cookies won’t work correctly.</p><h3>Common Mistakes Developers Make</h3><h3>1. Using Wildcard in Production</h3><p>Bad:</p><pre>&#39;allowed_origins&#39; =&gt; [&#39;*&#39;]</pre><p>Good:</p><pre>&#39;allowed_origins&#39; =&gt; [<br>    &#39;https://app.yourdomain.com&#39;<br>]</pre><p>Using * can expose APIs unnecessarily.</p><h3>2. Forgetting to Clear Config Cache</h3><p>After modifying:</p><pre>config/cors.php</pre><p>Run:</p><pre>php artisan optimize:clear</pre><p>Many CORS issues are simply cached configuration problems.</p><h3>3. Thinking Postman Tests CORS</h3><p>Postman works because:</p><pre>Postman does NOT enforce CORS</pre><p>Browsers enforce CORS.</p><p>So:</p><pre>Works in Postman<br>Fails in Browser</pre><p>is completely normal.</p><h3>4. HTTPS Certificate Problems</h3><p>Sometimes CORS errors are actually SSL issues.</p><p>Example:</p><pre>Frontend → HTTPS<br>Backend → Invalid SSL Certificate</pre><p>The browser may report a CORS error even though SSL is the real problem.</p><h3>Debugging Checklist</h3><p>When facing a CORS error:</p><ul><li>Verify config/cors.php</li><li>Check frontend URL</li><li>Check allowed methods</li><li>Check allowed headers</li><li>Verify Sanctum settings</li><li>Verify SSL certificate</li><li>Clear Laravel cache</li><li>Check browser Network tab</li><li>Verify OPTIONS request succeeds</li></ul><h3>Best Practices</h3><p>✅ Allow only trusted domains</p><p>✅ Restrict methods where possible</p><p>✅ Avoid wildcard origins in production</p><p>✅ Review CORS before deployment</p><p>✅ Monitor API security regularly</p><p>✅ Use HTTPS in production</p><h3>Final Thoughts</h3><p>CORS is not a Laravel bug.</p><p>It is a browser security feature designed to protect users and applications from unauthorized cross-origin access. Understanding how origins, preflight requests, and Laravel’s CORS configuration work will save hours of debugging and help you build more secure APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2bb24908cd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Large Database Handling: Complete Guide for High-Performance Applications]]></title>
            <link>https://medium.com/@devrekha/laravel-large-database-handling-complete-guide-for-high-performance-applications-938beedee1e4?source=rss-49f97b15a16d------2</link>
            <guid isPermaLink="false">https://medium.com/p/938beedee1e4</guid>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[high-performance]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[large-datasets]]></category>
            <dc:creator><![CDATA[Rekha Patel]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 08:01:01 GMT</pubDate>
            <atom:updated>2026-06-03T08:01:01.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKjJqfq7v8jLa9C5fpjREw.png" /></figure><p>If your Laravel application has thousands or millions of records, using Model::all() can quickly exhaust memory and slow down your application. Laravel provides several optimized methods to process large datasets efficiently.</p><p>This guide explains when to use each method, common pitfalls, and real-world examples.</p><h3>Why Large Dataset Handling Matters</h3><p>Many developers start with:</p><pre>$users = User::all();</pre><p>This works fine for a few hundred records but becomes problematic when your table grows.</p><p>Problems:</p><ul><li>High memory usage</li><li>Slow response times</li><li>PHP memory limit exceeded</li><li>Database timeouts</li></ul><p>Laravel offers better alternatives depending on your use case.</p><h3>1. all() — Load Everything</h3><h3>Example</h3><pre>$users = User::all();</pre><h3>When to Use</h3><ul><li>Small tables</li><li>Admin settings</li><li>Reference data</li></ul><h3>Pros</h3><p>✅ Simple</p><h3>Cons</h3><p>❌ Loads entire result set into memory</p><p>❌ Not suitable for large tables</p><h3>2. chunk() — Process Records in Batches</h3><h3>Example</h3><pre>User::chunk(1000, function ($users) {<br>    foreach ($users as $user) {<br>        // Process user<br>    }<br>});</pre><p>Laravel retrieves records in multiple batches using LIMIT/OFFSET queries.</p><h3>Best For</h3><ul><li>Sending emails</li><li>Reports</li><li>Imports/exports</li></ul><h3>Pros</h3><p>✅ Low memory usage</p><p>✅ Easy implementation</p><h3>Cons</h3><p>❌ Records may be skipped or duplicated if rows are inserted/deleted during processing.</p><h3>3. chunkById() — Safe Batch Processing</h3><h3>Example</h3><pre>User::chunkById(1000, function ($users) {<br>    foreach ($users as $user) {<br>        $user-&gt;processed = 1;<br>        $user-&gt;save();<br>    }<br>});</pre><p>Instead of OFFSET, Laravel uses the primary key to fetch the next batch.</p><h3>Best For</h3><ul><li>Updating records</li><li>Deleting records</li><li>Background processing</li></ul><h3>Pros</h3><p>✅ Safer than chunk()</p><p>✅ No skipped records during updates</p><h3>Cons</h3><p>❌ Requires an indexed unique column (typically id) for best results.</p><h3>4. lazy() — Stream Data Like a Collection</h3><h3>Example</h3><pre>User::lazy()-&gt;each(function ($user) {<br>    // Process user<br>});</pre><p>Laravel internally processes records in chunks but exposes them as a single stream via a LazyCollection.</p><h3>Best For</h3><ul><li>Memory-efficient iteration</li><li>Collection pipelines</li></ul><h3>Pros</h3><p>✅ Cleaner syntax</p><p>✅ Lower memory consumption</p><h3>Cons</h3><p>❌ Can still encounter issues when updating records while iterating. Use lazyById() instead.</p><h3>5. lazyById() — Safe Lazy Processing</h3><h3>Example</h3><pre>User::lazyById()-&gt;each(function ($user) {<br>    $user-&gt;status = &#39;processed&#39;;<br>    $user-&gt;save();<br>});</pre><p>Uses primary-key-based pagination while providing LazyCollection behavior.</p><h3>Best For</h3><ul><li>Updating large datasets</li><li>Queue processing</li><li>Data migration</li></ul><h3>Pros</h3><p>✅ Memory efficient</p><p>✅ Safe for updates</p><h3>6. cursor() — One Record at a Time</h3><h3>Example</h3><pre>foreach (User::cursor() as $user) {<br>    // Process user<br>}</pre><p>Uses a generator and yields records one at a time rather than loading everything into memory.</p><h3>Best For</h3><ul><li>CSV exports</li><li>Read-only processing</li><li>Huge datasets</li></ul><h3>Pros</h3><p>✅ Extremely low memory usage</p><p>✅ Single query execution</p><h3>Cons</h3><p>❌ Cannot eager load relationships efficiently</p><p>❌ Long-running database connection</p><p>❌ Some database drivers may still buffer results internally.</p><h3>7. paginate() — Standard Pagination</h3><h3>Example</h3><pre>$users = User::paginate(20);</pre><p>Laravel performs a count query and retrieves paginated results.</p><h3>Best For</h3><ul><li>Admin panels</li><li>Data tables</li></ul><h3>Pros</h3><p>✅ Shows total pages</p><p>✅ Easy navigation</p><h3>Cons</h3><p>❌ Additional COUNT query</p><h3>8. simplePaginate() — Faster Pagination</h3><h3>Example</h3><pre>$users = User::simplePaginate(20);</pre><p>Avoids the total count query, making it faster.</p><h3>Best For</h3><ul><li>Next/Previous navigation</li></ul><h3>Pros</h3><p>✅ Better performance</p><h3>Cons</h3><p>❌ No total page count</p><h3>9. cursorPaginate() — Best for Huge Tables</h3><h3>Example</h3><pre>$users = User::orderBy(&#39;id&#39;)<br>            -&gt;cursorPaginate(20);</pre><p>Uses cursor-based pagination instead of OFFSET. Laravel recommends it for large datasets because it scales much better than offset pagination.</p><h3>SQL Comparison</h3><p>Offset pagination:</p><pre>SELECT * FROM users<br>ORDER BY id<br>LIMIT 20 OFFSET 100000;</pre><p>Cursor pagination:</p><pre>SELECT * FROM users<br>WHERE id &gt; 100000<br>ORDER BY id<br>LIMIT 20;</pre><h3>Best For</h3><ul><li>Infinite scroll</li><li>Social feeds</li><li>Millions of records</li></ul><h3>Pros</h3><p>✅ Fastest pagination</p><p>✅ No OFFSET scanning</p><h3>10. select() — Retrieve Only Required Columns</h3><h3>Bad</h3><pre>User::all();</pre><h3>Good</h3><pre>User::select(&#39;id&#39;, &#39;name&#39;, &#39;email&#39;)-&gt;get();</pre><h3>Benefits</h3><p>✅ Less memory</p><p>✅ Faster queries</p><p>✅ Less network transfer</p><h3>11. with() — Eliminate N+1 Queries</h3><h3>Bad</h3><pre>$users = User::all();</pre><pre>foreach ($users as $user) {<br>    echo $user-&gt;posts-&gt;count();<br>}</pre><p>May execute hundreds or thousands of extra queries.</p><h3>Good</h3><pre>$users = User::with(&#39;posts&#39;)-&gt;get();</pre><h3>Benefits</h3><p>✅ Significant performance improvement</p><p>✅ Fewer database queries</p><h3>12. insert() — Bulk Insert</h3><h3>Bad</h3><pre>foreach ($records as $record) {<br>    User::create($record);<br>}</pre><h3>Good</h3><pre>User::insert($records);</pre><h3>Benefits</h3><p>✅ One query instead of thousands</p><h3>13. upsert() — Insert or Update</h3><h3>Example</h3><pre>User::upsert(<br>    $records,<br>    [&#39;email&#39;],<br>    [&#39;name&#39;, &#39;phone&#39;]<br>);</pre><p>Updates existing rows and inserts new ones in a single operation.</p><h3>Best For</h3><ul><li>Data synchronization</li><li>ERP integrations</li><li>CRM imports</li></ul><h3>14. Caching Queries</h3><h3>Example</h3><pre>$users = Cache::remember(<br>    &#39;active_users&#39;,<br>    3600,<br>    fn() =&gt; User::where(&#39;active&#39;, 1)-&gt;get()<br>);</pre><h3>Benefits</h3><p>✅ Reduced database load</p><p>✅ Faster responses</p><h3>15. Queue Jobs for Heavy Tasks</h3><h3>Example</h3><pre>ProcessUsersJob::dispatch();</pre><p>Instead of processing 500,000 records in a web request:</p><ul><li>Push work to queue</li><li>Process in background</li><li>Improve user experience</li></ul><h3>16. Database Indexes (Most Important)</h3><p>Many developers optimize PHP code while ignoring indexes.</p><h3>Example</h3><pre>Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>    $table-&gt;index(&#39;email&#39;);<br>});</pre><h3>Benefits</h3><p>✅ Faster searching</p><p>✅ Faster sorting</p><p>✅ Faster joins</p><h3>Recommended Decision Matrix</h3><p>ScenarioRecommended MethodSmall tableall()Read millions of recordscursor()Batch processingchunk()Updating large datasetschunkById()Stream large datalazy()Stream + updatelazyById()Standard UI paginationpaginate()Fast paginationsimplePaginate()Huge datasets / infinite scrollcursorPaginate()Avoid N+1 querieswith()Bulk insertinsert()Insert or updateupsert()</p><h3>Final Recommendation</h3><p>For production SaaS applications:</p><ol><li>Never use all() on large tables.</li><li>Prefer chunkById() for updates.</li><li>Prefer cursorPaginate() for large listings.</li><li>Use select() to fetch only required columns.</li><li>Always add proper indexes.</li><li>Move heavy processing to queues.</li><li>Use eager loading (with()) to avoid N+1 issues.</li></ol><p>These practices can reduce memory usage dramatically and keep Laravel applications responsive even with millions of database records. Official Laravel documentation also recommends cursor pagination for large datasets where performance is critical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=938beedee1e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>