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
Laravel 8 Inner Join Query Example
Laravel 8 Inner Join Query Exa...

In this tutorial we will learn about laravel 8 inner join query example. Also see how to join two tables in laravel 8. I...

Read More

Nov-24-2021

How To Use OpenAI In Laravel 8/9
How To Use OpenAI In Laravel 8...

In this article, we will explore the integration of OpenAI into Laravel versions 8, 9, and 10. Our focus will be on unde...

Read More

Feb-06-2023

Laravel 10 Change Column Name And Type In Migration
Laravel 10 Change Column Name...

In this article, we will see laravel 10 change column names and data types in migration. Here, we will learn about...

Read More

Apr-19-2023

Disable Sorting On Specific Columns In Datatable
Disable Sorting On Specific Co...

In this article, we will delve into the process of disabling sorting for specific columns in Datatables. If you find the...

Read More

Aug-24-2020