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

问题描述

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

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

CartController.PHP

>>> import re
>>> x = "emma is good developer. emma is a writer. emmanuel is her brother."
>>> re.sub("[^A-Za-z]+"," ",f" {x} ").count(" emma ")
2

cart.blade.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();
    }

}

web.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

解决方法

关于Laravel的想法不多,但是javascript中的此解决方案将使您了解如何继续...

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

您必须更改一些代码:

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方法来获取最新产品,而无需刷新页面。

,

我开始忘记Laravel,而且我身边没有人,所以下面的代码只是理论上的。

首先,您需要一个后端才能即时更新数量。这只是您的“常规”更新,但它将返回带有新createSurveyResult(surveyResults) { let token = Vue.prototype.$auth.getLocalStorage( `${this.activeUser.uuid}_${process.env.NODE_ENV}_${ACCESS_TOKEN}` ); if (token) { axiosModified.defaults.headers.common["Authorization"] = `Bearer ${token}`; } return Promise.all( surveyResults.map((payload) => axiosModified.post("/feedback/results/",payload) ) ); } 的JSON。

total

为此的新路线:

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'); quantity

total

神奇之处在于<!-- 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