In this guide, I’ll show you how to connect Python's powerful data analysis capabilities, specifically using Pandas, to your Laravel application. By integrating Python scripts with Laravel, you can perform real-time data analysis, making it easier to extract insights directly from your application.
This setup is ideal for projects that require complex data processing without overloading PHP, enabling efficient handling of large datasets.
Let’s dive into a step-by-step tutorial on integrating Python into Laravel using Pandas, where we’ll set up an API endpoint in Laravel, call a Python script, and fetch real-time insights.
Real-Time Data Analysis in Laravel with Python
To integrate Python into your Laravel application, ensure you have Python installed on your server. If not, install it using the following commands based on your operating system:
sudo apt update
sudo apt install python3 python3-pip
Next, install the required Python libraries. We’ll use Pandas for data processing and Flask to create a small API that Laravel can call.
pip3 install pandas flask
In this example, we’ll create a Python script that performs a simple data analysis task. Save the following Python script as data_analysis.py
from flask import Flask, request, jsonify
import pandas as pd
import json
app = Flask(__name__)
@app.route('/analyze', methods=['POST'])
def analyze():
# Get JSON data from the POST request
data = request.json
# Convert data to a Pandas DataFrame
df = pd.DataFrame(data)
# Perform data analysis (example: calculate mean of a column)
result = df.mean().to_dict()
# Return the result as JSON
return jsonify(result)
if __name__ == '__main__':
app.run(port=5001)
In this script:
Run the Python script to start the Flask server:
python3 data_analysis.py
The server will now be listening on port 5001. Laravel will send data to this endpoint for analysis.
Now, let’s create a controller in Laravel to interact with the Python API. In your Laravel project directory, create a new controller.
php artisan make:controller DataAnalysisController
Open DataAnalysisController.php and add the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class DataAnalysisController extends Controller
{
public function analyzeData(Request $request)
{
// Sample data for analysis
$data = [
['value' => 10, 'quantity' => 15],
['value' => 20, 'quantity' => 25],
['value' => 30, 'quantity' => 35],
];
// Send data to the Python API
$response = Http::post('http://localhost:5001/analyze', $data);
// Get the response data
$result = $response->json();
return response()->json([
'success' => true,
'data' => $result
]);
}
}
In this code:
$data
) to simulate the dataset for analysis.Http
client, we send a POST request to the Python server (http://localhost:5001/analyze
) with the data.
Open routes/web.php and add a route to handle the data analysis request:
use App\Http\Controllers\DataAnalysisController;
Route::get('/analyze-data', [DataAnalysisController::class, 'analyzeData']);
Now, when you visit http://your-laravel-app-url/analyze-data, Laravel will send the data to the Python server for analysis and return the processed results.
php artisan serve
.python3 data_analysis.py
.http://127.0.0.1:8000/analyze-data
in your browser or use a tool like Postman to test the endpoint.
You can modify data_analysis.py to perform any analysis that Pandas offers, like data filtering, aggregation, or more complex computations
You might also like:
In this example, I will show you how to delete multiple records using a single checkbox or how to delete multi...
May-26-2020
Greetings, developers! If you've encountered the frustrating "Laravel Mix is not recognized as an internal...
Dec-29-2023
In this tutorial we will see laravel 8 many to many polymorphic relationship. many to many polymorphic relationship more...
Nov-22-2021
In this article, we will see laravel 9 generate PDF from HTML using TCPDF. Here, we will learn how to integrate tcpdf in...
Jan-31-2023