Real-Time Data Analysis in Laravel with Python

Websolutionstuff | Nov-19-2024 | Categories : Laravel Python

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

Real-Time Data Analysis in Laravel with Python

 

Step 1: Setting Up Your Environment

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

 

Step 2: Create a Python Script for Data Analysis

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:

  • We use Flask to create an API endpoint (/analyze).
  • The analyze function reads JSON data, converts it into a Pandas DataFrame, performs a basic analysis (calculating the mean of each column), and returns the results as JSON.

 

Step 3: Run the Flask Server

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.

 

Step 4: Create a Laravel Controller

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:

  • We define a sample data array ($data) to simulate the dataset for analysis.
  • Using Laravel’s Http client, we send a POST request to the Python server (http://localhost:5001/analyze) with the data.
  • The response from the Python server is parsed and returned as a JSON response in Laravel

 

Step 5: Set Up a Route for Data Analysis

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.

 

Step 6: Testing the Integration
  1. Start the Laravel server by running php artisan serve.
  2. Start the Flask server by running python3 data_analysis.py.
  3. Visit http://127.0.0.1:8000/analyze-data in your browser or use a tool like Postman to test the endpoint.

 

Step 7: Customize Your Data Analysis

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:

Recommended Post
Featured Post
How To Delete Multiple Records Using Checkbox In Laravel
How To Delete Multiple Records...

In this example, I will show you how to delete multiple records using a single checkbox or how to delete multi...

Read More

May-26-2020

Laravel mix is not recognized as an internal or external command
Laravel mix is not recognized...

Greetings, developers! If you've encountered the frustrating "Laravel Mix is not recognized as an internal...

Read More

Dec-29-2023

Laravel 8 Many To Many Polymorphic Relationship
Laravel 8 Many To Many Polymor...

In this tutorial we will see laravel 8 many to many polymorphic relationship. many to many polymorphic relationship more...

Read More

Nov-22-2021

Laravel 9 Generate PDF From HTML Using TCPDF
Laravel 9 Generate PDF From HT...

In this article, we will see laravel 9 generate PDF from HTML using TCPDF. Here, we will learn how to integrate tcpdf in...

Read More

Jan-31-2023