如何在Laravel中实现条形码扫描并将对应明细数据存入MySQL?
基于Laravel实现扫码枪条码数据入库方案
扫码枪本质是模拟键盘输入设备,扫描完成后会自动输出条码内容并触发回车事件,不需要额外适配驱动,整体实现分为前后端两部分:
前端实现(负责捕获扫码数据)
- 页面新增一个常驻/隐藏的输入框,设置
autofocus属性,确保扫码时焦点默认落在该输入框内,避免内容输入错位 - 监听输入框的回车事件,触发后取输入框内容作为条码值,调用后端接口提交数据
前端示例代码:
const scanInput = document.getElementById('barcode-input'); scanInput.addEventListener('keydown', e => { // 识别扫码完成的回车事件 if(e.keyCode === 13 && scanInput.value.trim()) { fetch('/api/inventory/save', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }, body: JSON.stringify({ barcode: scanInput.value.trim(), quantity: 20, // 实际业务可替换为表单填写的真实数量 color: '红色' // 可替换为预设值或从条码规则解析出的属性值 }) }).then(res => res.json()).then(data => { // 提交成功后清空输入框,等待下一次扫码 scanInput.value = ''; scanInput.focus(); }) } })
后端Laravel实现
1. 数据库准备
创建库存表迁移文件,执行命令:php artisan make:migration create_inventories_table
编辑迁移文件逻辑:
public function up() { Schema::create('inventories', function (Blueprint $table) { $table->id(); $table->string('barcode')->index(); // 存储条形码值 $table->integer('quantity'); // 库存数量 $table->string('color')->nullable(); // 颜色属性,非必填可设为nullable // 可按需扩展其他库存字段 $table->timestamps(); }); }
执行php artisan migrate生成数据表,然后创建对应模型:php artisan make:model Inventory
配置模型可批量赋值字段:
// app/Models/Inventory.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Inventory extends Model { protected $fillable = [ 'barcode', 'quantity', 'color' ]; }
2. 路由配置
在routes/api.php中新增接口路由:
use App\Http\Controllers\InventoryController; Route::post('/inventory/save', [InventoryController::class, 'store']);
3. 控制器逻辑实现
创建控制器:php artisan make:controller InventoryController
编写存储逻辑:
// app/Http/Controllers/InventoryController.php namespace App\Http\Controllers; use App\Models\Inventory; use Illuminate\Http\Request; class InventoryController extends Controller { public function store(Request $request) { // 参数校验 $validated = $request->validate([ 'barcode' => 'required|string', 'quantity' => 'required|integer|min:1', 'color' => 'nullable|string' ]); // 新增库存场景直接创建 Inventory::create($validated); // 同条码叠加库存场景可替换为以下逻辑 // $inventory = Inventory::firstOrNew(['barcode' => $validated['barcode']]); // $inventory->quantity += $validated['quantity']; // $inventory->color = $validated['color'] ?? $inventory->color; // $inventory->save(); return response()->json([ 'code' => 200, 'msg' => '库存数据存储成功' ]); } }
如果你需要从条码本身解析出明细属性(比如条码规则中包含颜色、规格信息),只需在控制器store方法中新增对应的条码解析逻辑即可,无需修改前端扫码捕获逻辑。
内容的提问来源于stack exchange,提问作者Md. Tazimul Islam Raj
相关产品推荐
相关产品推荐

