




本文详解在 laravel 8 中安全、高效地将百万级手机号(源自 textarea)批量插入数据库的完整方案,规避内存溢出、超时错误与 http 500 问题,推荐使用流式分批 + 内存控制 + 命令行替代方案。
在 Web 请求中一次性处理 1,000,000 行数据(如从
✅ 正确做法是:边解析、边过滤、边组装、边插入,严格控制单批次内存占用,并彻底避免累积百万级对象于内存中。
以下是优化后的核心逻辑(修复原代码关键缺陷):
public function mobile_store(Request $request)
{
$request->validate(['mobile' => 'required|string']);
// 按行分割(兼容 \r\n、\n、\r)
$lines = preg_split('/[\r\n]+/', trim($request->mobile), -1, PREG_SPLIT_NO_EMPTY);
// 使用集合去重(保留顺序,避免 array_unique 重索引问题)
$uniqueLines = collect($lines)->unique()->filter(function ($line) {
return strlen(trim($line)) >= 10; // 至少 10 位有效数字
})->map(function ($line) {
$clean = trim($line);
// 统一格式:+98 + 后10位数字(自动截取,防超长)
return '+98' . substr($clean, -10);
});
// 流式分批插入:每 5000 条执行一次 insert,不累积全部数据
$batch = [];
$totalInserted = 0;
$now = Carbon::now();
foreach ($uniqueLines as $mobile) {
$batch[] = [
'mobile' => $mobile,
'created_at' => $now,
'updated_at' => $now,
];
if (count($batch) >= 5000) {
Mobile::insert($batch);
$totalInserted += count($batch);
$batch = []; // 立即释放内存
}
}
// 插入剩余不足 5000 条的数据
if (!empty($batch)) {
Mobile::insert($batch);
$totalInserted += count($batch);
}
return redirect()
->back()->with('success', "成功插入 {$totalInserted} 条唯一手机号");
}⚠️ 关键优化说明:
? 进阶建议(强烈推荐用于百万级场景):
迁移到 Artisan 命令(最佳实践)
将导入逻辑封装为命令行任务,彻底绕过 Web 超时与内存限制:
php artisan mobile:import --file=/path/to/mobiles.txt
命令中可启用 DB::transaction()、使用 DB::table()->upsert()(Laravel 9+)、或结合 cursor() 分页读取大文件。
前端配合优化
数据库层面调优
? 总结:Web 请求不适合百万级同步导入。当前方案可稳定处理 50 万行以内;超大规模务必转向 CLI 命令 + 文件流式处理 + 数据库调优组合策略,兼顾稳定性、可观测性与运维友好性。