Integrating AI Services with Laravel: Step-by-Step Tutorial for Beginners

Integrating AI services into your Laravel application can significantly enhance its capabilities, allowing you to add features like natural language processing, image recognition, and more. This step-by-step tutorial is designed for beginners who want to incorporate AI APIs into their Laravel projects efficiently.

Prerequisites

  • Basic knowledge of PHP and Laravel framework
  • Laravel installed on your local machine
  • Composer package manager
  • An AI service provider account (e.g., OpenAI, Google Cloud AI, IBM Watson)
  • API key from your chosen AI provider

Step 1: Set Up a New Laravel Project

Open your terminal and create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel ai-integration

Navigate into your project directory:

cd ai-integration

Step 2: Install HTTP Client

Laravel includes Guzzle HTTP client by default. Ensure it’s installed and configured:

composer require guzzlehttp/guzzle

Step 3: Store Your API Key

Securely store your API key in the environment variables. Open .env and add:

AI_API_KEY=your_api_key_here

Step 4: Create a Service to Handle AI Requests

Generate a new service class to manage API calls:

php artisan make:service AiService

Alternatively, create a new PHP file app/Services/AiService.php with the following content:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class AiService
{
    protected $apiKey;
    protected $apiUrl;

    public function __construct()
    {
        $this->apiKey = env('AI_API_KEY');
        $this->apiUrl = 'https://api.example.com/v1/endpoint'; // Replace with your AI provider's API endpoint
    }

    public function sendRequest($data)
    {
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->apiKey,
            'Content-Type' => 'application/json',
        ])->post($this->apiUrl, $data);

        return $response->json();
    }
}

Step 5: Create a Controller to Handle User Input

Generate a new controller:

php artisan make:controller AiController

In app/Http/Controllers/AiController.php, add:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\AiService;

class AiController extends Controller
{
    protected $aiService;

    public function __construct(AiService $aiService)
    {
        $this->aiService = $aiService;
    }

    public function index()
    {
        return view('ai_form');
    }

    public function process(Request $request)
    {
        $input = $request->input('user_input');

        $response = $this->aiService->sendRequest([
            'prompt' => $input,
            'max_tokens' => 100,
        ]);

        return view('ai_result', ['response' => $response]);
    }
}

Step 6: Create Views for User Interaction

Create a Blade template resources/views/ai_form.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>AI Integration</title>
</head>
<body>
    <h1>Enter Your Prompt</h1>
    <form action="/process" method="POST">
        @csrf
        <textarea name="user_input" rows="4" cols="50"></textarea><br>
        <button type="submit">Send</button>
    </form>
</body>
</html>

Create another Blade template resources/views/ai_result.blade.php to display the AI response:

<!DOCTYPE html>
<html>
<head>
    <title>AI Response</title>
</head>
<body>
    <h1>AI Response</h1>
    <p><strong>Response:</strong> {{ $response['choices'][0]['text'] ?? 'No response' }}</p>
    <a href="/">Try Again</a>
</body>
</html>

Step 7: Define Routes

Open routes/web.php and add:

use App\Http\Controllers\AiController;

Route::get('/', [AiController::class, 'index']);
Route::post('/process', [AiController::class, 'process']);

Step 8: Test Your Application

Start the Laravel development server:

php artisan serve

Open your browser and navigate to http://localhost:8000. Enter a prompt and submit to see the AI response.

Conclusion

By following these steps, you have successfully integrated an AI service into your Laravel application. You can now expand this setup to include more complex interactions, additional AI features, or connect to different AI providers based on your project needs.