【问题标题】:How to update the total price of an item according to its quantity?如何根据数量更新商品的总价?
【发布时间】:2020-12-10 12:59:43
【问题描述】:

我正在开发一个购物车网站。在我的购物车页面上,应根据该商品的数量更新商品的总价。 https://github.com/darryldecode/laravelshoppingcart 我安装了这个购物车包。

如何根据数量更新商品的总价?

CartController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use App\Category;
use Darryldecode\Cart\Cart;

class CartController extends Controller
{
   
    public function index()
    {
       // $cartItems = \Cart::session(auth()->id())->getContent();
        
         return view ('cart');
     }
   

    public function show($id)
    {
        $product = Product::find($id);
       
        return view('cart')->with(compact('product'));
   }


    public function update($rowId)
    {

        \Cart::session(auth()->id())->update($rowId, [
            'quantity' => [
            'relative' => true, 
            'value'=> request('quantity')
            ]
            ]);
        return back();
        
    }


    public function destroy($itemId)
    {

        \Cart::session(auth()->id())->remove($itemId);
        
        return back();
        
    }

    public function addtocart(Product $product)
    {
    
        \Cart::session(auth()->id())->add(array(
            'id' => $product->id,
            'name' => $product->prod_name,
            'price' => $product->prod_price,
            'quantity' => 1,
            'attributes' => array(),
            'associatedModel' => $product
                 ));
                
                 return redirect()->back();
    }

}

cart.blade.php

                        @foreach(\Cart::session(auth()->id())->getContent() as $items)
                            <tr>
                            <form class="mb-4" action="{{route('cart.update',$items->id)}}">    
                            
                                <td data-title="Product">
                                    <a href="#" class="text-gray-90">{{ $items ['name'] }}</a>
                                </td>
                            
                                <td data-title="Price">
                                    <span class="">LKR {{ $items ['price'] }}.00</span>
                                </td>
                            
                                <td data-title="Quantity">
                                    <span class="sr-only">Quantity</span>
                                    <!-- <form class="mb-4" action="{{route('cart.update',$items->id)}}"> -->
                                        <br>
                                        <div class="border rounded-pill py-1 width-122 w-xl-80 px-3 border-color-1">
                                             <div class="js-quantity row align-items-center">
                                                <div class="col">
                                                    <input class="js-result form-control h-auto border-0 rounded p-0 shadow-none" name="quantity" type="text" value="{{$items->quantity}}">
                                                </div>
                                                    <div class="col-auto pr-1">
                                                    <a class="js-minus btn btn-icon btn-xs btn-outline-secondary rounded-circle border-0" href="javascript:;">
                                                        <small class="fas fa-minus btn-icon__inner"></small>
                                                    </a>
                                                    <a class="js-plus btn btn-icon btn-xs btn-outline-secondary rounded-circle border-0" href="javascript:;">
                                                        <small class="fas fa-plus btn-icon__inner"></small>
                                                    </a>
                                                </div> 
                                            </div>
                                        </div>
                                    <!-- </form> -->
                                </td>

                                 
                                                
                                        <!-- Quantity -->
                                        <!-- <div class="border rounded-pill py-1 width-122 w-xl-80 px-3 border-color-1">
                                            <div class="js-quantity row align-items-center">
                                                <div class="col">
                                                    <input class="js-result form-control h-auto border-0 rounded p-0 shadow-none" name="quantity" type="number" value="{{$items->quantity}}">
                                                    <button type="submit" class="btn btn-soft-secondary mb-3 mb-md-0 font-weight-normal px-5 px-md-4 px-lg-5 w-100 w-md-auto">Update cart</button>
                                                </div>
                                                <div class="col-auto pr-1">
                                                    <a class="js-minus btn btn-icon btn-xs btn-outline-secondary rounded-circle border-0" href="javascript:;">
                                                        <small class="fas fa-minus btn-icon__inner"></small>
                                                    </a>
                                                    <a class="js-plus btn btn-icon btn-xs btn-outline-secondary rounded-circle border-0" href="javascript:;">
                                                        <small class="fas fa-plus btn-icon__inner"></small>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>  -->
                                   
                                    <!-- End Quantity -->
                                </td>
                                
                                <td data-title="Total">
                                    <span class="">
                                    LKR  {{Cart::session(auth()->id())->get($items->id)->getPriceSum()}}.00
                                    </span>
                                </td>
                                
                                    <td>
                                         <button type="submit" class="btn btn-soft-secondary mb-3 mb-md-0 font-weight-normal px-5 px-md-4 px-lg-5 w-100 w-md-auto"><i class="fas fa-pen-nib text-primary fa-2x"></i></button>
                                         <a href="{{ route('cart.destroy', $items->id)}}" class="btn btn-soft-secondary mb-3 mb-md-0 font-weight-normal px-5 px-md-4 px-lg-5 w-100 w-md-auto"><i class="fas fa-trash-alt text-danger fa-2x"></i></a>
                                    </td>
                               
                                <!-- <td>
                                    <div class="d-md-flex">
                                        <form class="mb-4" action="{{route('cart.update',$items->id)}}">
                                            <button type="submit" class="btn btn-soft-secondary mb-3 mb-md-0 font-weight-normal px-5 px-md-4 px-lg-5 w-100 w-md-auto">Update cart</button>
                                            <a href="../shop/checkout.html" class="btn btn-primary-dark-w ml-md-2 px-5 px-md-4 px-lg-5 w-100 w-md-auto d-none d-md-inline-block">Proceed to checkout</a>
                                        </form>
                                    </div>
                                </td> -->
                                </form>
                             </tr>
                         @endforeach

web.php

Route::get('/cart', 'CartController@index')->name('cart.index')->middleware('auth');;
Route::get('/cart/{cartItems}', 'CartController@add')->name('cart.add')->middleware('auth');
Route::get('/cart/destroy/{itemId}', 'CartController@destroy')->name('cart.destroy')->middleware('auth');
Route::get('/cart/update/{itemId}', 'CartController@update')->name('cart.update')->middleware('auth');
Route::get('/add-to-cart/{product}','CartController@addtocart')->name('addToCart');

【问题讨论】:

  • 当您从购物车中删除商品时,它应该会根据文档自动更新总数。你能告诉我发生了什么吗
  • 其实我的要求是当我们增加数量时,该商品的总价也需要增加,没有更新按钮。它不会自动更新。
  • 在我的代码中,如果我更改数量金额,那么我应该点击更新按钮,那么只有总金额会根据数量进行更新。 @KamleshPaul
  • 你是说修改数量表格后,表格应该自动提交到后端,并生成总价显示在前端?
  • @paudel 当然是的。

标签: php laravel e-commerce


【解决方案1】:

我开始忘记 Laravel 并且我附近没有 Laravel,所以下面的代码只是理论上的。

首先,您需要一个能够即时更新数量的后端。这只是您的“正常”更新,但它会返回带有新 total 的 JSON。

public function updateQuantity($rowId)
{
    \Cart::session(auth()->id())->update($rowId, [
        'quantity' => [
        'relative' => true, 
        'value'=> request('quantity')
        ]
        ]);
    $newTotal = Cart::session(auth()->id())->get($items->id)->getPriceSum();
    return [ 'total' => $newTotal ];
}

为此的新路线:

Route::get('/cart/updateQuantity/{itemId}', 'CartController@updateQuantity')->name('cart.updateQuantity')->middleware('auth');

现在我们需要准备前端以便能够动态更新quantitytotal

<!-- we will change this line: -->
<input class="js-result form-control h-auto border-0 rounded p-0 shadow-none" name="quantity" type="number" value="{{$items->quantity}}">
<!-- to this line: -->
<input class="js-result form-control h-auto border-0 rounded p-0 shadow-none" name="quantity" id="quantity{{$items->id}}" data-id="{{$items->id}}" type="number" value="{{$items->quantity}}" onchange="updateQuantity({{$items->id}})">
<!-- yes, we just added ID to be able to use this later, and added callback -->
<!-- after previous line with "input" we can add an element to keep the route,
  this is because routes are calculated by Laravel dynamically -->
<span id="updateQuantityRoute{{$items->id}}" style="display:none">{{route('cart.updateQuantity',$items->id)}}</span>

<!-- also we need to prepare "total", so this line: -->
<span class="">{{Cart::session(auth()->id())->get($items->id)->getPriceSum()}}</span>
<!-- change to this line: -->
<span class="" id="total{{$items->id}}">{{Cart::session(auth()->id())->get($items->id)->getPriceSum()}}</span>

所以神奇在于updateQuantity函数:

function updateQuantity(itemId) {
  // here I will use jQuery just to show the idea
  const route = $('#updateQuantityRoute' + itemId);
  const newQuantity = $('#quantity' + itemId).val();
  $.post(route, {'quantity': newQuantity}).done(function( data ) {
    // here we have response
    if (typeof data === 'string') data = JSON.parse(data);
    const updatedTotal = data.total;
    $('#total' + itemId).innerText = updatedTotal; // update in DOM
  });
}

【讨论】:

    【解决方案2】:

    您必须更改一些代码:

    1- 添加新的路线和方法来检索所有卡片项目

    Route::get('/cart/items', 'CartController@allItems')->name('cart.all-items')->middleware('auth');
    

    方法:

    public function allItems()
        {
          return \Cart::session(auth()->id())->getContent();
        }
    

    2- 接下来,您需要将此代码块移动并更改为 Javascript,并通过 Ajax 从上述路由中检索数据。

     @foreach(\Cart::session(auth()->id())->getContent() as $items)
                                    <tr>
                                        <td class="text-center">
                                        <a href="{{ route('cart.destroy', $items->id)}}">x</a>
                                        </td>
                                        <td data-title="Product">
                                            <a href="#" class="text-gray-90">{{ $items ['name'] }}</a
                                        </td>
                                        <td data-title="Price">
                                            <span class="">LKR {{ $items ['price'] }}.00</span>
                                        </td>
                                        <td data-title="Quantity">
                                            <span class="sr-only">Quantity</span>
                                            <!-- Quantity -->
                                            <div class="border rounded-pill py-1 width-122 w-xl-80 px-3 border-color-1">
                                                <div class="js-quantity row align-items-center">
                                                    <div class="col">
                                                        <input class="js-result form-control h-auto border-0 rounded p-0 shadow-none" name="quantity" type="text" value="{{$items->quantity}}">
                                                    </div>
                                                    <div class="col-auto pr-1">
                                                        <a class="js-minus btn btn-icon btn-xs btn-outline-secondary rounded-circle border-0" href="javascript:;">
                                                            <small class="fas fa-minus btn-icon__inner"></small>
                                                        </a>
                                                        <a class="js-plus btn btn-icon btn-xs btn-outline-secondary rounded-circle border-0" href="javascript:;">
                                                            <small class="fas fa-plus btn-icon__inner"></small>
                                                        </a>
                                                    </div>
                                                </div>
                                            </div> 
                                            <!-- End Quantity -->
                                        </td>
                                        <td data-title="Total">
                                            <span class="">
                                                {{Cart::session(auth()->id())->get($items->id)->getPriceSum()}}
                                            </span>
                                        </td>
                                    @endforeach
    
    

    每当有新产品添加到您的卡片或通过间隔计时器时,您都可以调用 Javascript 的方法来获取最新产品,而无需刷新页面。

    【讨论】:

    • 如果您需要更多关于javascript方法的信息,我可以为您补充更多细节。
    【解决方案3】:

    关于 Laravel 的想法不多,但是这个 javascript 解决方案会让你知道如何继续......

    function getPriceSum() {
        YOUR_ARRAY.reduce((sum, item) => { return sum + (item.price * item.quantity), 0 })
    }
    

    【讨论】:

    • 谢谢,但是当我们增加或减少数量时,我的要求需要改变。为此,如何在不使用按钮继续的情况下获得该值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2021-05-26
    • 1970-01-01
    • 2021-11-16
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多