Skip to content

Commit

Permalink
商品加入购物车
Browse files Browse the repository at this point in the history
  • Loading branch information
leo108 committed Dec 22, 2018
1 parent 58db149 commit 845907c
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 0 deletions.
35 changes: 35 additions & 0 deletions app/Http/Controllers/CartController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddCartRequest;
use App\Models\CartItem;
use Illuminate\Http\Request;

class CartController extends Controller
{
public function add(AddCartRequest $request)
{
$user = $request->user();
$skuId = $request->input('sku_id');
$amount = $request->input('amount');

// 从数据库中查询该商品是否已经在购物车中
if ($cart = $user->cartItems()->where('product_sku_id', $skuId)->first()) {

// 如果存在则直接叠加商品数量
$cart->update([
'amount' => $cart->amount + $amount,
]);
} else {

// 否则创建一个新的购物车记录
$cart = new CartItem(['amount' => $amount]);
$cart->user()->associate($user);
$cart->productSku()->associate($skuId);
$cart->save();
}

return [];
}
}
46 changes: 46 additions & 0 deletions app/Http/Requests/AddCartRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Http\Requests;

use App\Models\ProductSku;

class AddCartRequest extends Request
{
public function rules()
{
return [
'sku_id' => [
'required',
function ($attribute, $value, $fail) {
if (!$sku = ProductSku::find($value)) {
return $fail('该商品不存在');
}
if (!$sku->product->on_sale) {
return $fail('该商品未上架');
}
if ($sku->stock === 0) {
return $fail('该商品已售完');
}
if ($this->input('amount') > 0 && $sku->stock < $this->input('amount')) {
return $fail('该商品库存不足');
}
},
],
'amount' => ['required', 'integer', 'min:1'],
];
}

public function attributes()
{
return [
'amount' => '商品数量'
];
}

public function messages()
{
return [
'sku_id.required' => '请选择商品'
];
}
}
21 changes: 21 additions & 0 deletions app/Models/CartItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CartItem extends Model
{
protected $fillable = ['amount'];
public $timestamps = false;

public function user()
{
return $this->belongsTo(User::class);
}

public function productSku()
{
return $this->belongsTo(ProductSku::class);
}
}
5 changes: 5 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@ public function favoriteProducts()
->withTimestamps()
->orderBy('user_favorite_products.created_at', 'desc');
}

public function cartItems()
{
return $this->hasMany(CartItem::class);
}
}
34 changes: 34 additions & 0 deletions database/migrations/2018_12_22_071404_create_cart_items_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCartItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cart_items', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('product_sku_id');
$table->foreign('product_sku_id')->references('id')->on('product_skus')->onDelete('cascade');
$table->unsignedInteger('amount');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cart_items');
}
}
35 changes: 35 additions & 0 deletions resources/views/products/show.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,41 @@ class="btn sku-btn"
});
});
// 加入购物车按钮点击事件
$('.btn-add-to-cart').click(function () {
// 请求加入购物车接口
axios.post('{{ route('cart.add') }}', {
sku_id: $('label.active input[name=skus]').val(),
amount: $('.cart_amount input').val(),
})
.then(function () { // 请求成功执行此回调
swal('加入购物车成功', '', 'success');
}, function (error) { // 请求失败执行此回调
if (error.response.status === 401) {
// http 状态码为 401 代表用户未登陆
swal('请先登录', '', 'error');
} else if (error.response.status === 422) {
// http 状态码为 422 代表用户输入校验失败
var html = '<div>';
_.each(error.response.data.errors, function (errors) {
_.each(errors, function (error) {
html += error+'<br>';
})
});
html += '</div>';
swal({content: $(html)[0], icon: 'error'})
} else {
// 其他情况应该是系统挂了
swal('系统错误', '', 'error');
}
})
});
});
</script>
@endsection
1 change: 1 addition & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@
Route::post('products/{product}/favorite', 'ProductsController@favor')->name('products.favor');
Route::delete('products/{product}/favorite', 'ProductsController@disfavor')->name('products.disfavor');
Route::get('products/favorites', 'ProductsController@favorites')->name('products.favorites');
Route::post('cart', 'CartController@add')->name('cart.add');
});
Route::get('products/{product}', 'ProductsController@show')->name('products.show');

0 comments on commit 845907c

Please sign in to comment.