Laravel 12 Import Excel File Into Database Using Python

In Laravel 12, different methods can be used to import Excel files into the database. While Laravel provides libraries like maatwebsite/excel, using Python with Pandas can make data processing more flexible.

In this guide, I will show you how to set up a Laravel API to receive Excel data and use Python to read the file and send it to Laravel.

Importing an Excel file into a Laravel 12 database using Python efficiently handles bulk data processing. Laravel provides a powerful backend for managing database operations, while Python’s Pandas library makes it easy to read and process Excel files.

In this tutorial, I will walk you through the process of reading an Excel file using Python, sending the data to a Laravel API, and inserting it into the database.

By the end of this guide, you will be able to:

  1. Read Excel files using Python
  2. Validate and filter data before sending it to Laravel
  3. Create an API in Laravel 12 to handle data import
  4. Process large Excel files efficiently using queues

Laravel 12 Import Excel File Into Database Using Python

Laravel 12 Import Excel File Into Database Using Python

 

Step 1: Install Laravel 12 and Set Up a Migration

If you haven't installed Laravel 12, set it up:

laravel new excel-import
cd excel-import
php artisan migrate

Create a migration for the users table:

php artisan make:migration create_users_table

Update the migration file:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
};

Run the migration:

php artisan migrate

 

Step 2: Define the API Route in routes/api.php

Modify your routes/api.php file to point to a dedicated controller:

use App\Http\Controllers\UserImportController;

Route::post('/import-users', [UserImportController::class, 'importUsers']);

 

Step 3: Create the Controller

Generate a new controller using Artisan:

php artisan make:controller UserImportController

Now, open app/Http/Controllers/UserImportController.php and add the following code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserImportController extends Controller
{
    public function importUsers(Request $request)
    {
        $request->validate([
            'users' => 'required|array',
            'users.*.name' => 'required|string',
            'users.*.email' => 'required|email',
        ]);

        $usersToInsert = [];

        foreach ($request->users as $user) {
            if (!User::where('email', $user['email'])->exists()) {
                $usersToInsert[] = [
                    'name' => $user['name'],
                    'email' => $user['email'],
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
        }

        if (!empty($usersToInsert)) {
            User::insert($usersToInsert); // Bulk insert for performance
        }

        return response()->json(['message' => 'Users imported successfully!']);
    }
}

 

Example (Using Queue Job for Importing Users)

Run:

php artisan queue:table
php artisan migrate

Create a job:

php artisan make:job ImportUsersJob

Modify app/Jobs/ImportUsersJob.php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImportUsersJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $users;

    public function __construct(array $users)
    {
        $this->users = $users;
    }

    public function handle()
    {
        User::insert($this->users);
    }
}

Modify UserImportController.php

use App\Jobs\ImportUsersJob;

public function importUsers(Request $request)
{
    $request->validate([
        'users' => 'required|array',
        'users.*.name' => 'required|string',
        'users.*.email' => 'required|email|unique:users,email',
    ]);

    dispatch(new ImportUsersJob($request->users));

    return response()->json(['message' => 'Users import started!']);
}

Run queue worker:

php artisan queue:work

 

Step 4: Read and Send Data Using Python

Install required Python packages:

pip install pandas requests

Create a Python script (import_excel.py):

import pandas as pd
import requests

# Read Excel file
df = pd.read_excel("example.xlsx")

# Convert data to JSON
data = {"users": df.to_dict(orient="records")}

# Send data to Laravel API
response = requests.post("http://127.0.0.1:8000/api/import-users", json=data)

if response.status_code == 200:
    print(response.json())  # Output Laravel's success response
else:
    print(f"Error: {response.status_code} - {response.text}")  # Show error response

 

Step 5: Start Laravel Server and Run the Script

Start the Laravel server:

php artisan serve

Run the Python script:

python import_excel.py

 


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