In this tutorial, I will show you how to integrate Python machine learning models with Laravel 11. By connecting Laravel to a Python-based machine learning API, you can enhance your web application with powerful predictive analytics features.
This step-by-step guide will walk you through setting up the connection between Laravel and Python, allowing you to pass data from Laravel to your machine learning model and retrieve predictions seamlessly.
Integrating Python Machine Learning with Laravel 11
First, let's create a simple Python Flask API that will serve your machine learning model. We'll use Flask to expose the model through an API endpoint that Laravel can interact with.
Install Flask and required libraries:
pip install Flask scikit-learn
Sample Python machine learning model (Flask API):
from flask import Flask, request, jsonify
from sklearn.linear_model import LinearRegression
import numpy as np
app = Flask(__name__)
# Dummy training data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])
# Train a simple Linear Regression model
model = LinearRegression()
model.fit(X, y)
@app.route('/predict', methods=['POST'])
def predict():
# Get input data from the request
data = request.get_json()
values = np.array(data['input']).reshape(-1, 1)
# Make prediction
prediction = model.predict(values)
# Return prediction as JSON response
return jsonify({'prediction': prediction.tolist()})
if __name__ == '__main__':
app.run(debug=True)
How it works:
/predict
endpoint that accepts input data via a POST request and returns the prediction from a simple linear regression model.Run the Flask server:
python app.py
Now, let's set up Laravel to interact with the Python API:
composer create-project laravel/laravel my-laravel-app
Install Guzzle HTTP Client:
To send HTTP requests from Laravel to the Flask API, we will use Guzzle, which is a simple HTTP client.
composer require guzzlehttp/guzzle
Create a new controller in Laravel that will send data to the Python API and receive predictions.
php artisan make:controller MLController
Edit the MLController
as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class MLController extends Controller
{
public function predict(Request $request)
{
// Validate input data
$validatedData = $request->validate([
'input' => 'required|array',
'input.*' => 'numeric',
]);
// Prepare data for the Python API
$inputData = [
'input' => $validatedData['input']
];
// Send request to the Python Flask API
$client = new Client();
$response = $client->post('http://127.0.0.1:5000/predict', [
'json' => $inputData
]);
// Decode the response from the Python API
$result = json_decode($response->getBody()->getContents(), true);
// Return the prediction result
return response()->json($result);
}
}
How it works:
MLController
sends the input data from a Laravel form or request to the Python API using Guzzle.
Next, set up a route to access the machine learning prediction functionality.
Edit routes/web.php
use App\Http\Controllers\MLController;
Route::post('/predict', [MLController::class, 'predict']);
Now, create a simple form in Laravel to collect data and send it to the machine learning model.
Create a Blade template resources/views/predict.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Machine Learning Prediction</title>
</head>
<body>
<h1>Predict Using Machine Learning Model</h1>
<form action="/predict" method="POST">
@csrf
<label for="input">Enter input values:</label><br>
<input type="text" name="input[]" placeholder="Value 1"><br>
<input type="text" name="input[]" placeholder="Value 2"><br>
<input type="text" name="input[]" placeholder="Value 3"><br>
<button type="submit">Predict</button>
</form>
@if (session('prediction'))
<h2>Prediction Result: {{ session('prediction') }}</h2>
@endif
</body>
</html>
How it works:
/predict
endpoint when submitted.
Finally, modify the MLController
to pass the prediction result back to the view.
public function predict(Request $request)
{
// Same code as before...
// Store the prediction result in session and redirect
return redirect()->back()->with('prediction', $result['prediction']);
}
Now, when you enter values in the form and click Predict, Laravel will send the data to the Python machine learning model and display the prediction result on the page.
You might also like: