You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9电商项目:从Session提取购物车数据存入orders表

Laravel 9 购物车结账数据入库实现

步骤1:获取并遍历购物车数据

你的Session购物车是以商品ID为键的数组,每个元素包含商品的标题、数量和价格。首先遍历这个数组,逐个处理每个商品:

// 从Session取出购物车数据
$cart = session('cart');

// 遍历每个商品
foreach ($cart as $item) {
    // 拆分数据,注意将价格转换为数值类型(原数据是字符串)
    $order_title = $item['title'];
    $order_price = (float)$item['price'];
    $order_quantity = $item['quantity'];

    // 下面将数据存入数据库
}

步骤2:将数据存入orders表

你可以选择使用Laravel的DB门面或者Eloquent模型来完成入库操作:

方式一:使用DB门面直接操作

use Illuminate\Support\Facades\DB;

// 遍历购物车时执行插入
foreach ($cart as $item) {
    $order_title = $item['title'];
    $order_price = (float)$item['price'];
    $order_quantity = $item['quantity'];

    DB::table('orders')->insert([
        'title' => $order_title,
        'price' => $order_price,
        'quantity' => $order_quantity,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
}

// 结账完成后清空购物车(可选但推荐)
session()->forget('cart');

方式二:使用Eloquent模型(更符合Laravel规范)

首先确保你有对应的Order模型:

// app/Models/Order.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    // 允许批量赋值的字段
    protected $fillable = ['title', 'price', 'quantity'];
}

然后在控制器中使用模型创建订单记录:

use App\Models\Order;

// 遍历购物车执行创建
foreach ($cart as $item) {
    Order::create([
        'title' => $item['title'],
        'price' => (float)$item['price'],
        'quantity' => $item['quantity'],
    ]);
}

session()->forget('cart');

注意事项

  • 确保orders表的字段类型正确:title为字符串类型,price建议用decimal(10,2)(存储精确的金额),quantity为整数类型,同时包含created_at和updated_at时间字段(Laravel默认支持)。
  • 如果需要关联当前登录用户,可在入库时添加user_id字段,值为auth()->id(),记得在模型的$fillable中加入user_id。

内容的提问来源于stack exchange,提问作者jack_22_08

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:45:39