当您更改价格时,Laravel Ajax购物车会动态更改小计



我试图在更改数量时动态更改小计,但失败了,我是Ajax的新手,我似乎不知道如何实现这一点,如果有人帮助,我将不胜感激

控制器:

public function quantity (Request $request)
{
$carts = Cart::all();
$carts->quantity = $request->quantity;
$carts->save();
return response()->json([
'quantity' => $carts->quantity,
]);
}

刀片:

html:

<input class="cart-plus-minus-box qty" type="number" id="qty" name="qty" value="1" >

js:

$( document ).ready(function() {
$(".qty").change(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('checkout.qty') }}", 
data: {
'quantity': qty.value
}, 
type: "get",
success: function(result) {

}
});
});
});

web.php

Route::get('/checkout/qty','CheckoutController@quantity')->name('checkout.qty');

推车数据库:

Schema::create('carts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->timestamps();
});

代码中的问题是行

// Here, $carts is a collection of models.
$carts = Cart::all();
// Here, you're treating $carts as if it was a single model.
$carts->quantity = $request->quantity;
$carts->save();

如果要更新所有Carts,则应使用update()方法。

Cart::update(['quantity' => $request->quantity]);

如果您想将更新约束到Carts的特定子集,可以通过添加where()方法来实现。

Cart::where(...)->update(['quantity' => $request->quantity]);

要使这样的大规模更新工作,字段'quantity'应该位于Card模型中的$fillable数组中。

class Cart extends Model
{
protected $fillable = [
'quantity',
];
}

另一方面,如果您想更新单个购物车,您可以使用find()通过其id或经过一组过滤器后的first()来缩小其范围。

$cart = Cart::find(1);
$cart->quantity = $request->quantity;
$cart->save();
$cart = Cart::where(...)->first();
$cart->quantity = $request->quantity;
$cart->save();

现在,如果您真的想创建一个新的购物车,您可以按照以下方式进行。

$cart = new Cart;
$cart->quantity = $request->quantity;
$cart->save();

但是,这可能会引发错误,因为根据迁移,user_idproduct_id字段不能为null。

此外,根据您的迁移,您的carts表没有数量字段。要么将其添加到您现有的迁移中,然后再次迁移所有

class CreateCartsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('quantity')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('carts');
}
}

或者进行新的迁移,专门将列添加到表中。

class AddQuantityColumnToCartsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('carts', function (Blueprint $table) {
$table->integer('quantity')->after('product_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('carts', function (Blueprint $table) {
$table->dropColumn('quantity');
});
}
}

最新更新