Laravel 13 - How to Integrate Groq API Using Prism.

Touseef Afridi
13 May 26

Laravel 13 - How to Integrate Groq API Using Prism.

In this tutorial, we will learn how to integrate Groq API in Laravel 13 using the Prism package. We will build a real-time AI chat application with Tailwind CSS and AJAX, enabling dynamic responses powered by Groq LLMs.

Quick Overview

This guide walks you through setting up a fresh Laravel 13 application and integrating Groq API using the Prism package. You start by creating a new Laravel project with a minimal setup, then install and configure Prism along with your Groq API key in the .env file. After that, you create a controller to handle the chat logic, define routes for sending and receiving messages, and build a Blade view using Tailwind CSS for the chat interface. The frontend uses AJAX to send user prompts to the backend, where Prism communicates with Groq’s Llama model and returns responses that are displayed dynamically in the chat window with a loading state for a smooth, interactive experience.

Step # 1 : Install Laravel 13 for Your Groq Project.

Before integrating Groq with Prism, we first need a fresh Laravel 13 application. Make sure Composer is installed on your system since Laravel depends on it for package management. It’s also recommended to install the Laravel Installer globally for faster project creation. If you don’t already have the Installer, run the following command.
composer global require laravel/installer
Next, create a new Laravel 13 project using the following command.
laravel new groq
During the installation process, Laravel will ask you to choose a few configuration options. Select the following settings.
  • Starter kit → Choose None to keep the project clean and minimal.

  • Testing framework → Select Pest for a modern testing experience.

  • Laravel Boost → Choose No since it is not required for this project.

  • Database → Select SQLite for a lightweight database setup.

  • Run npm install and build assets → Choose Yes to prepare frontend assets automatically.

Once the installation is complete, you’ll have a clean Laravel 13 project ready for building your Groq AI integration with Prism.

Step # 2 : Move Into the Project Directory.

Once your Laravel 13 project has been created, open your preferred terminal such as Command Prompt, Git Bash, or any other terminal of your choice, then navigate to the project directory.
cd c:/xampp/htdocs/groq
You are now inside your Laravel application and ready to install packages and start building features.

Step # 3 : Install Prism for AI Integration.

Now, we’ll install Prism, a Laravel package that makes integrating AI providers much easier. It provides a single, clean interface for working with AI providers such as Groq, OpenAI, Gemini, and more, without tying your code to any one provider. Run the following Composer command to install it.
composer require prism-php/prism
Once the installation is complete, Prism is ready to be configured in your project.

Step # 4 : Publish Prism Configuration File.

Now that Prism is installed, we need to generate its configuration file so we can control and customize its behavior. To do that, run the following command in your terminal.
php artisan vendor:publish --tag=prism-config
This will add a Prism config file inside your Laravel config directory, where you can easily adjust its settings based on your project needs.

Step # 5 : Set Up Groq API Key and Environment Configuration.

To generate your API key, follow these steps.
  1. Go to Groq Console: https://console.groq.com/ and sign in or create your account.

  2. After logging in, click on API Keys.



  3. Then click Create API Key.



  4. Give your key a name, set an expiration if needed, and click Submit.



  5. A popup will appear showing your API key. Copy it and store it safely, as you won’t be able to view it again.



Now open your .env file and add the following line.
GROQ_API_KEY=your_groq_api_key_here
Replace your_groq_api_key_here with the key you copied from the Groq Console, then save the file. If you change the environment variable name (GROQ_API_KEY), make sure to update it in config/prism.php as well. At this point, your Laravel application is ready to securely communicate with the Groq API using Prism.

Step # 6 : Build the Controller to Handle Groq Requests.

Next, we’ll create a controller that will manage the AI workflow from displaying the interface to processing user prompts and returning responses from Groq. Create the controller using the Artisan command below.
php artisan make:controller AIController
After that, open app/Http/Controllers/AIController.php and replace its content with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Prism\Prism\Facades\Prism;
use Prism\Prism\Enums\Provider;
class AIController extends Controller
{
    // Return the main view where users will interact with Groq
    public function index()
    {
        return view('groq');
    }
    // Handle incoming AJAX request
    public function ask(Request $request)
    {
        // Validate prompt input
        $request->validate([
            'prompt' => 'required|string'
        ]);
        // Send prompt to Groq using Prism
        $response = Prism::text()
        // Specify provider and use Meta's recent Llama 4 Scout instruct model
        ->using(Provider::Groq, 'meta-llama/llama-4-scout-17b-16e-instruct')
        // Attach user prompt
        ->withPrompt($request->prompt)
        // Return plain text response
        ->asText();
        // Return JSON response
        return response()->json([
            'answer' => $response->text
        ]);
    }
}
At this point, your controller is fully configured to act as the bridge between your frontend and Groq. The index() method loads the main interface, while the ask() method processes incoming user prompts, validates the request, sends it to Groq through Prism using Meta’s Llama 4 Scout model, and returns a clean JSON response that can be consumed directly by the frontend.

Step # 7 : Set Up Routes for Groq Integration.

Now we need to wire everything together by connecting our controller methods to URLs. This allows the application to display the interface and handle AI requests. Open your routes/web.php file and import the controller.
use App\Http\Controllers\AIController;
Then define the following routes.
// Display the Groq chat interface
Route::get('/groq', [AIController::class, 'index']);
// Process user prompt and return AI response
Route::post('/groq', [AIController::class, 'ask']);
Here, the GET /groq route is used to load the chat interface, and the POST /groq route processes user prompts and returns the AI-generated response through Prism using Groq.

Step # 8 : Build the Groq Chat Interface.

Now we’ll create the frontend for our AI chat application where users can interact with Groq. Inside the resources/views directory, create a new file named: groq.blade.php. This file will contain the complete chat interface built using Tailwind CSS along with JavaScript to handle asynchronous messaging. Paste the following code into it.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Code Shotcut - Laravel 13 Integrating Groq Using Prism</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        #chatBox::-webkit-scrollbar {
            width: 6px;
        }
        #chatBox::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 10px;
        }
        #chatBox::-webkit-scrollbar-track {
            background: transparent;
        }
    </style>
</head>
<body class="bg-gray-100 text-gray-900">
<div class="h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-4xl h-full flex flex-col rounded-2xl overflow-hidden
                border border-gray-200 bg-white shadow-xl">
        <!-- Header -->
        <div class="px-6 py-4 flex items-center justify-between border-b border-gray-200 bg-gray-50">
            <div>
                <h1 class="text-lg font-semibold text-gray-800">Code Shotcut</h1>
                <p class="text-xs text-gray-500">
                    Laravel 13 integrating Groq using Prism
                </p>
            </div>
            <div class="w-3 h-3 rounded-full bg-emerald-500 shadow-sm"></div>
        </div>
        <!-- Chat -->
        <div id="chatBox" class="flex-1 overflow-y-auto px-6 py-6 space-y-5 bg-gray-50">
            <div class="text-center text-gray-400 text-sm mt-10">
                ⚡ Start chatting with Groq AI
            </div>
        </div>
        <!-- Chat Input Section -->
        <div class="p-4 border-t border-gray-200 bg-white">
            <div class="flex items-end gap-3">
                <textarea id="prompt"
                          rows="1"
                          class="flex-1 bg-gray-100 border border-gray-200 rounded-xl px-4 py-3 text-sm
                                 focus:outline-none focus:ring-2 focus:ring-emerald-400
                                 placeholder:text-gray-400 resize-none overflow-hidden"
                          placeholder="Ask Groq anything..."></textarea>
                <button onclick="sendMessage()"
                        class="bg-emerald-600 hover:bg-emerald-500
                               px-6 py-3 rounded-xl text-sm font-medium
                               text-white shadow-md transition">
                    Send
                </button>
            </div>
        </div>
    </div>
</div>
<script>
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
const promptInput = document.getElementById('prompt');
/* Send message on Enter */
promptInput.addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});
/* Auto resize input box */
promptInput.addEventListener('input', function () {
    this.style.height = 'auto';
    this.style.height = this.scrollHeight + 'px';
});
/* Append message to chat */
function appendMessage(html) {
    let chatBox = document.getElementById('chatBox');
    chatBox.innerHTML += html;
    /* Auto scroll to latest message */
    chatBox.scrollTop = chatBox.scrollHeight;
}
/* Send message to backend */
async function sendMessage() {
    let prompt = promptInput.value.trim();
    if (!prompt) return;
    /* User message */
    appendMessage(`
        <div class="flex justify-end items-start gap-3">
            <div class="bg-emerald-600 text-white px-4 py-3 rounded-2xl max-w-[75%] text-sm shadow">
                ${prompt}
            </div>
        </div>
    `);
    promptInput.value = '';
    promptInput.style.height = 'auto';
    /* Loading indicator */
    let loaderId = Date.now();
    appendMessage(`
        <div id="${loaderId}" class="flex items-start gap-3">
            <div class="w-9 h-9 rounded-full bg-emerald-500 flex items-center justify-center text-white text-xs font-bold">
                AI
            </div>
            <div class="bg-white border border-gray-200 px-4 py-3 rounded-2xl text-sm text-gray-500 animate-pulse">
                Thinking...
            </div>
        </div>
    `);
    try {
        let response = await fetch('/groq', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': token
            },
            body: JSON.stringify({ prompt })
        });
        let data = await response.json();
        document.getElementById(loaderId).remove();
        /* AI response */
        appendMessage(`
            <div class="flex items-start gap-3">
                <div class="w-9 h-9 rounded-full bg-emerald-500 flex items-center justify-center text-white text-xs font-bold">
                    AI
                </div>
                <div class="bg-white border border-gray-200 px-4 py-3 rounded-2xl
                            max-w-[75%] text-sm text-gray-700 leading-relaxed shadow-sm">
                    ${data.answer}
                </div>
            </div>
        `);
    } catch (error) {
        document.getElementById(loaderId).remove();
        appendMessage(`
            <div class="flex items-start gap-3">
                <div class="w-9 h-9 rounded-full bg-red-500 flex items-center justify-center text-white text-xs font-bold">
                    !
                </div>
                <div class="bg-red-50 border border-red-200 px-4 py-3 rounded-2xl
                            max-w-[75%] text-sm text-red-500">
                    Failed to connect with Groq API.
                </div>
            </div>
        `);
    }
}
</script>
</body>
</html>
The groq.blade.php view uses Tailwind CSS to build a clean and responsive chat interface with a message window, input area, and send button, while JavaScript handles asynchronous communication by sending requests to the /groq route, receiving responses from the Laravel backend powered by Prism and Groq, and updating the chat dynamically without page reloads. It also includes auto-scrolling, a loading indicator, and dynamic message rendering to ensure a smooth and interactive user experience.

Step # 9 : Run and Test the Groq Integration.

Now it’s time to bring everything together and see our Groq AI chat in action. Start the Laravel development server using.
php artisan serve
Once the server starts, open your browser and visit: http://127.0.0.1:8000/groq. You should now see your Groq AI chat interface built with Tailwind.


Try sending a message using the chat interface it will be sent to your Laravel backend, processed through Prism with Groq, and the AI response will appear instantly in the chat window. This confirms that your Laravel 13 Groq integration is working as expected.

Conclusion

By following this guide, you have successfully set up a Laravel 13 application and integrated Groq API using the Prism package. You learned how to install and configure Prism, connect your Groq API key, create a controller to handle requests, define routes, and build a real-time chat interface using a Blade view with Tailwind CSS. You also implemented AJAX to send user prompts and display AI-generated responses dynamically with a loading state for a smooth and interactive experience. This gives you a solid foundation to build more advanced AI-powered features in Laravel applications, such as chat assistants, automation tools, or intelligent content generation systems.
For more details, refer to the official Prism documentation: https://github.com/prism-php/prism.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering