【问题标题】:How can I add Laravel Crinsane cart data as an order?如何将 Laravel Crinsane 购物车数据添加为订单?
【发布时间】:2020-02-18 10:39:37
【问题描述】:

为了从基于 Crinsane 的购物车创建订单并将其关联到(经过身份验证的)用户,我创建了 Order 模型并在订单控制器中尝试了以下操作。

<?php

namespace App\Http\Controllers;

use Cart;
use App\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }
    /**
     * store cart to authenticated user as order.
     *
     */
    public function store(Request $request)
    {
        $order = new Order;

        $cartcontent = Cart::content();
        $user = auth('api')->user();
        $serializedcontent = $cartcontent->toJson(); //Returns []
        //$serializedcontent = $cartcontent->toArray(); //error
        //$serializedcontent = str_replace("\0", "~~NULL_BYTE~~", serialize($cartcontent)); //returns 0:29:"Illuminate....

        $order->user_id= $user->id;
        $order->cart_content= $serializedcontent;
        $order->save();

    }
}

编辑:

我尝试将列类型作为 TEXT(没有序列化)以及 JSON。我使用 Json API 进行前端 (Vue) 和 JWT 进行身份验证。

当我序列化为 JSON 时,该列会生成一个空集 []。如果我不序列化,它会返回O:29:"Illuminate\Support\Collection":1:{s:8:"~~NULL_BYTE~~*~~NULL_BYTE~~items";a:0:{}}

订购型号:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
        protected $fillable = [
        'user_id','user_id','cart_content'
    ];
        public function User(){
        return $this->belongsTo('App\User');
    }
}

来源链接:https://github.com/riyaz7us/Laraman/tree/master/app/Http/Controllers

【问题讨论】:

    标签: laravel eloquent shopping-cart laravel-6 laravel-controller


    【解决方案1】:

    来自docs

    Cart::content() 当然你也想得到购物车的内容。这 是您将使用内容方法的地方。此方法将返回一个 CartItems 的集合,您可以对其进行迭代并显示 内容给您的客户。

    您正试图在数据库中插入一个集合。您需要从基于current instance of the Crinsane 的卡中获取数据,然后将数据插入数据库中 json 或任何适合您的需求。

    【讨论】:

    • 还是不行。编辑购物车控制器存储方法:Cart::instance('shopping')-&gt;add([//products]) 。修改订单控制器为Cart::instance('shopping')-&gt;content();。它返回O:29:"Illuminate\Support\Collection":1:{s:8:"。当序列化或 json 时,它返回一个空数组
    • 你能用更多代码编辑你的帖子吗?你如何序列化它?您的数据库列的类型是什么?您的应用程序中是否为 mysql 启用了严格类型?您如何获取/重新运行数据库结果以显示它?它是作为 JSON 保存在数据库中还是只是空字符串?你能提供订单的模型吗?可填充、受保护、隐藏等。laravel.com/docs/5.8/eloquent-serialization 这是有关如何序列化数据的文档的链接
    • 编辑了问题。为方便起见,还添加了源链接
    • 谢谢。我不知道为什么您在可填充项中有 2 次 user_id 但您可以删除其中之一。另请查看github.com/Crinsane/LaravelShoppingcart/blob/master/src/… 这是store() 方法,可以解决您的问题。
    • 我现在明白了。我在 web 路由(用于会话)中使用了我的购物车控制器,并在 api 路由中使用了结帐控制器。无论如何,如果我使用 vue、vuex 商店而不是 crinsane 来存储我的购物车会怎么样?
    猜你喜欢
    • 2017-05-29
    • 2019-06-20
    • 2017-11-05
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2021-06-16
    相关资源
    最近更新 更多