【问题标题】:Updating Database Field with AJAX Laravel使用 AJAX Laravel 更新数据库字段
【发布时间】:2019-05-31 06:49:10
【问题描述】:

当用户使用 POST 方法完成订单时,我试图通过从数据库中的产品数量中减去购物车项目数量来更新我的库存水平。每次我运行该方法时,都会发生成功功能,但该字段不更新不更新。

谁能告诉我为什么?

我的控制器:

public function index ()
{
    $products = Product::all();


    return view('products', compact('products'));
}


public function cart()

{
    return view('cart');
}

public function addToCart($id)
{
    $product = Product::find($id);

    if(!$product) {

        abort(404);

    }

    $cart = session()->get('cart');

    // if cart is empty then this will be the first product
    if(!$cart) {

        $cart = [
                $id => [
                    "name" => $product->name,
                    "quantity" => 1,
                    "price" => $product->unit_price
                ]
        ];

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }

    // if cart isnt empty then check if this product exist then increment quantity
    if(isset($cart[$id])) {

        $cart[$id]['quantity']++;

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');

    }

    // if item doesnt exist in cart then add to cart with quantity = 1
    $cart[$id] = [
        "name" => $product->name,
        "quantity" => 1,
        "price" => $product->unit_price
    ];

    session()->put('cart', $cart);

    return redirect()->back()->with('success', 'Product added to cart successfully!');
}

public function update(Request $request)
{
    if($request->id and $request->quantity)
    {
        $cart = session()->get('cart');

        $cart[$request->id]["quantity"] = $request->quantity;

        session()->put('cart', $cart);

        session()->flash('success', 'Cart updated successfully');
    }
}

public function remove(Request $request)
{
    if($request->id) {

        $cart = session()->get('cart');

        if(isset($cart[$request->id])) {

            unset($cart[$request->id]);

            session()->put('cart', $cart);
        }

        session()->flash('success', 'Product removed successfully');
    }
}

public function stock (Request $request)
{
    if($request->id and $request->quantity)
    {
        $cart = session()->get('cart');

        $cart[$request->id]['quantity'] = $request->quantity;

        $products = Product::all();

        $stock = $products->unit_stock;

        $quantity = $stock - $cart;

        return $quantity;
    }
}

我的路线:

Route::post('stock', 'ProductController@stock');

我的看法cart.blade.php:

@extends('layout')



@section('content')

<table id="cart" class="table table-hover table-condensed">
    <thead>
    <tr>
        <th style="width:50%">Product</th>
        <th style="width:10%">Price</th>
        <th style="width:8%">Quantity</th>
        <th style="width:22%" class="text-center">Subtotal</th>
        <th style="width:10%"></th>
    </tr>
    </thead>
    <tbody>

    <?php $total = 0 ?>

    @if(session('cart'))
        @foreach(session('cart') as $id => $details)

            <?php $total += $details['price'] * $details['quantity'] ?>

            <tr>
                <td data-th="Product">
                    <div class="row">

                        <div class="col-sm-9">
                            <h4 class="nomargin">{{ $details['name'] }}</h4>
                        </div>
                    </div>
                </td>
                <td data-th="Price">${{ $details['price'] }}</td>
                <td data-th="Quantity">
                    <input type="number" value="{{ $details['quantity'] }}" class="form-control quantity" />
                </td>
                <td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
                <td class="actions" data-th="">
                    <button class="btn btn-info btn-sm update-cart" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
                    <button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
                </td>
            </tr>
        @endforeach
    @endif

    </tbody>
    <tfoot>
    <tr class="visible-xs">
        <td class="text-center"><strong>Total {{ $total }}</strong></td>
    </tr>
    <tr>
        <td><a href="{{ url('/products') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
        <td colspan="2" class="hidden-xs"></td>
        <td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
    </tr>
    </tfoot>

    <div class="row">
       <div class="btn col-md-12">
           <a href="{{ url('/cart') }}" id="order-complete">Test</a>
       </div>

    </div>
</table>

<script type="text/javascript">

    $("#order-complete").click(function (e){
       e.preventDefault();

        var ele = $(this);

        $.ajax({
           url: '{{ url('stock') }}',
           method: "post",
           data: {_token: '{{ csrf_token() }}'},
           success: function () {

            window.location.reload();
           }
        });
    });
</script>

@endsection

【问题讨论】:

  • 您是否检查过 $cart 是否包含预期的数据?
  • 这似乎令人困惑。只要 $product 返回一个集合,$products->unit_stock 怎么能工作。
  • 1) 您永远不会将其保存在数据库中。 2) 我很惊讶您没有收到错误,因为 $products 是对象的集合,而不是单个产品。

标签: php mysql database laravel laravel-5


【解决方案1】:

我可以从您的代码中发现一些错误。

  1. 让我们关注 ajax 请求调用的函数。

这里的这一行告诉我有一个数据idquantity 正在发送。

if($request->id and $request->quantity)

从 Route 的外观来看,它在 body 中。但是在 ajax 函数中,除了 csrf 令牌之外,您没有包含任何数据。尝试添加idquantity 数据。这只是价值的假设。

       data: {_token: '{{ csrf_token() }}', id: 6, quantity: 2},

其次,此函数返回产品集合。

$products = Product::all();

因此,如果您想修改产品,您必须访问其索引。例如

$products[0]->unit_stock = 3; 
$products[0]->save();

或者正如 Lewis 所说,您可以使用 foreach 循环来迭代集合中的每个对象

【讨论】:

  • 老实说,我认为@Jeff 的代码逻辑存在缺陷。如果我错了,请纠正我,但您正在尝试更新已购买/添加到购物车的产品库存。因此,您需要保存该购物车中添加的每个产品的 ID,但您尚未完成。获得每个产品的 id 后,您可以使用该调用 find 函数并更新产品的数量。
【解决方案2】:

我可以看到几个可能导致此问题的潜在问题。首先,看起来您正试图通过加载包含所有产品的集合来一次性设置数据库中所有产品的库存,而不是循环/加载订单中包含的产品($request)。你在这里做这个;

$products = Product::all();

然后您尝试在此处更改集合中所有产品的库存

$stock = $products->unit_stock;

$quantity = $stock - $cart;

我想你应该在你的$cart 变量中有一个产品集合,你应该循环并加载以进行操作。一些伪代码来说明我的观点;

foreach($product in $cart){
  $loadedProduct        = Product::find($product);
  $loadedProduct->stock = $loadedProduct->stock - $product["quantity"];
  $loadedProduct->save(); 
}

您也没有在您提供的代码中保存任何产品。上面的伪代码中有一个例子。

【讨论】:

  • 嗨刘易斯,谢谢你,我明白了!只是几件事,在 foreach 语句中,“in”不被识别为语法,“as”是否合适?当我将其更改为此页面时,页面可以正常工作,但是当我现在在 Ajax 方法启动时收到 500 错误
  • 嘿。是的,“as”在这里是正确的,抱歉刚刚在 JS 中编写了类似的代码 :) 上面的代码只是伪代码。你有没有改变它以匹配你自己的?
  • 我需要改变什么?我只是将“stock”更改为“unit_stock”,因为这是数据库中的字段,这就是全部吗?
  • 很难确定,因为我看不到您的购物车对象。我只是从您发布的内容中猜测,但看起来您的购物车对象只是一组产品,其键设置为产品 ID?如果是这种情况,请在我发布的 foreach 中删除 products 密钥。在里面,只使用Product::find($product) 来加载产品。我现在正在使用移动设备,因此如果可以并且如果这些更改不起作用,我会在以后提供帮助。
  • 非常感谢!我已经更新了我的问题,所以你可以看到我的完整控制器
猜你喜欢
  • 1970-01-01
  • 2020-04-16
  • 2015-02-20
  • 2013-02-19
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2014-08-19
  • 2020-07-17
相关资源
最近更新 更多