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:
Laravel 12 Import Excel File Into Database Using Python
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
Modify your routes/api.php file to point to a dedicated controller:
use App\Http\Controllers\UserImportController;
Route::post('/import-users', [UserImportController::class, 'importUsers']);
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
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
Start the Laravel server:
php artisan serve
Run the Python script:
python import_excel.py
You might also like: