Integrate Python AI Libraries in Laravel for Smart Features

In this guide, I’ll walk you through integrating Python-based AI libraries, like TensorFlow, into a Laravel application. With Python’s powerful machine learning and data processing capabilities, we can create smarter features within Laravel projects, enabling us to handle complex computations and provide AI-driven insights directly within our application.

Step-by-Step Guide to Integrate Python AI Solutions into Laravel

Integrate Python AI Libraries in Laravel for Smart Features

 

Step 1: Install Python and Required AI Libraries

First, make sure Python is installed on your server or development environment. You can install Python packages like TensorFlow using pip.

# Install TensorFlow
pip install tensorflow

Make sure Python is set up and accessible globally, as Laravel will call Python scripts directly.

 

Step 2: Set Up a Python Script for AI Processing

Create a Python script that will handle the AI tasks. For example, let’s create predict.py to process data using TensorFlow.

# predict.py
import tensorflow as tf
import sys

# Example function to process input and return prediction
def make_prediction(data):
    # Simple placeholder logic for demonstration
    # In a real case, load and run a trained model
    prediction = f"Prediction for input {data}: [0.75 probability]"
    return prediction

if __name__ == "__main__":
    # Accept input data from Laravel
    input_data = sys.argv[1]
    print(make_prediction(input_data))

The script predict.py takes input data from Laravel, processes it, and outputs the prediction.

 

Step 3: Call the Python Script from Laravel

To connect Laravel with Python, we’ll use PHP’s exec function to call the predict.py script and capture its output. In Laravel, create a controller AiController.php

app/Http/Controllers/AiController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AiController extends Controller
{
    public function getPrediction(Request $request)
    {
        // Get the data from the request
        $data = $request->input('data');

        // Run the Python script with the data
        $command = escapeshellcmd("python3 /path/to/predict.py '$data'");
        $output = shell_exec($command);

        // Return the output as a response
        return response()->json(['prediction' => $output]);
    }
}

This method captures the AI prediction returned by the Python script and sends it as a JSON response.

 

Step 4: Create a Route to Access AI Predictions

Define a route in web.php to access the getPrediction function.

routes/web.php


use App\Http\Controllers\AiController;

Route::post('/get-prediction', [AiController::class, 'getPrediction']);

 

Step 5: Build the Frontend for Prediction Input

Finally, set up a simple HTML form to test the prediction feature. Add a new Blade file, ai-predict.blade.php

resources/views/ai-predict.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel AI Prediction</title>
</head>
<body>
    <h1>Get AI Prediction</h1>
    <form id="predictionForm">
        <label for="data">Enter Data:</label>
        <input type="text" id="data" name="data" required>
        <button type="submit">Get Prediction</button>
    </form>
    <div id="result"></div>

    <script>
        document.getElementById('predictionForm').onsubmit = async function(event) {
            event.preventDefault();
            let data = document.getElementById('data').value;

            const response = await fetch('/get-prediction', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ data })
            });
            const result = await response.json();
            document.getElementById('result').innerText = 'Prediction: ' + result.prediction;
        }
    </script>
</body>
</html>

This page lets users input data and receive predictions. When submitted, the form sends the data to our Laravel controller, which in turn calls the Python script and displays the AI-generated prediction.

 

Step 6: Test the Integration

Run your Laravel application, and access the form at http://your-laravel-app/ai-predict. Enter some data, submit, and you should see the AI-driven prediction based on your Python script

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS