- Vào file cart.blade.php :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>show cart</title>
</head>
<body>
<div class="cart_wrapper">
@include('products.components.cart_component')
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
function cartUpdate(event) {
event.preventDefault();
let urlUpdateCart = $('.update_cart_url').data('url');
let id = $(this).data('id');
let quantity = $(this).parents('tr').find('input.quantity').val();
$.ajax({
type: "GET",
url: urlUpdateCart,
data: {id: id,quantity: quantity},
success: function (data) {
if(data.code == 200){
$('.cart_wrapper').html(data.cart_component);
}
},
error: function () {
}
});
}
$(function () {
$(document).on('click','.cart_update',cartUpdate)
})
</script>
</body>
</html>
- Vào file components tạo file cart_component.blade.php :
<div class="cart">
<div class="container">
<div class="row">
<table class="table update_cart_url" data-url="{{route('updateCart')}}">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Ảnh sản phẩm</th>
<th scope="col">Tên sản phẩm</th>
<th scope="col">Giá sản phẩm</th>
<th scope="col">Số lượng</th>
<th scope="col">Tổng tiền</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@php
$total = 0;
@endphp
@foreach($carts as $id => $cartItem)
@php
$total += $cartItem['price'] * $cartItem['quantity'];
@endphp
<tr>
<th scope="row">{{ $id }}</th>
<td>
<img style="width: 100px; height: 100px;object-fit: contain"
src="{{ $cartItem['image'] }}" alt="">
</td>
<td>{{ $cartItem['name'] }}</td>
<td>{{ number_format($cartItem['price']) }} VND</td>
<td>
<input type="number" value="{{$cartItem['quantity']}}" min="1" class="quantity">
</td>
<td>{{ number_format($cartItem['price'] * $cartItem['quantity']) }} VND</td>
<td>
<a href="" data-id="{{$id}}" class="btn btn-primary cart_update">Cập nhật</a>
<a href="" class="btn btn-danger">Xóa</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="col-md-12">
<h2>Tổng: {{ number_format($total) }} VND</h2>
</div>
</div>
</div>
</div>
- Vào file web.php :
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
//show product for user add to cart
Route::get('/product','ProductController@index');
//add-to-cart
Route::get('/product/add-to-cart/{id}','ProductController@addToCart')->name('addToCart');
//showcart
Route::get('/product/show-cart','ProductController@showCart')->name('showCart');
//update cart
Route::get('/product/update-cart','ProductController@updateCart')->name('updateCart');
- Vào file ProductController.php :
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(){
$products = Product::latest()->get();
return view('products.index',compact('products'));
}
public function addToCart($id){
// session()->flush('cart');
$product = Product::find($id);
$cart = session()->get('cart');
if (isset($cart[$id])){
$cart[$id]['quantity'] = $cart[$id]['quantity'] + 1;
}else{
$cart[$id]= [
'name'=> $product->name,
'price'=> $product->price,
'quantity'=> 1,
'image'=> $product->image_path,
];
}
session()->put('cart', $cart);
return response()->json([
'code'=> 200,
'message'=>'success'
],200);
}
public function showCart(){
$carts = session()->get('cart');
return view('products.cart',compact('carts'));
}
public function updateCart(Request $request){
if ($request->id && $request->quantity){
$carts = session()->get('cart');
$carts[$request->id]['quantity'] = $request->quantity;
session()->put('cart', $carts);
$carts = session()->get('cart');
$cartComponent = view('products.components.cart_component',compact('carts'))->render();
return response()->json(['cart_component' => $cartComponent, 'code'=> 200],200);
}
}
}
- Vào file index.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Document</title>
</head>
<body>
<div class="products mt-5">
<div class="container">
<div class="row">
<div class="col-md-12">
<a href="{{route('showCart')}}" class="btn btn-primary mb-5">Show cart to checkout</a>
</div>
</div>
<div class="row">
@foreach($products as $product)
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{$product->image_path}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{$product->name}}</h5>
<p class="card-text">
{{number_format($product->price)}}đ
</p>
<p class="card-text">
{{$product->description}}
</p>
<a href="#"
data-url="{{route('addToCart',['id' => $product->id]) }}"
class="btn btn-primary add_to_cart">
Add to card
</a>
</div>
</div>
</div>
@endforeach
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
function addToCart(event) {
event.preventDefault();
let urlCart = $(this).data('url');
$.ajax({
type: "GET",
url:urlCart,
dataType: 'json',
success: function (data) {
if(data.code == 200){
alert('Thêm sản phẩm vào giỏ hàng thành công!')
}
},
error:function () {
}
});
};
$(function () {
$('.add_to_cart').on('click', addToCart);
})
</script>
</body>
</html>
kết quả:
Xóa card
- Vào web.php:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
//show product for user add to cart
Route::get('/product','ProductController@index');
//add-to-cart
Route::get('/product/add-to-cart/{id}','ProductController@addToCart')->name('addToCart');
//showcart
Route::get('/product/show-cart','ProductController@showCart')->name('showCart');
//update cart
Route::get('/product/update-cart','ProductController@updateCart')->name('updateCart');
//delete cart
Route::get('/product/delete-cart','ProductController@deleteCart')->name('deleteCart');
- Vào ProductController.php:
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(){
$products = Product::latest()->get();
return view('products.index',compact('products'));
}
public function addToCart($id){
// session()->flush('cart');
$product = Product::find($id);
$cart = session()->get('cart');
if (isset($cart[$id])){
$cart[$id]['quantity'] = $cart[$id]['quantity'] + 1;
}else{
$cart[$id]= [
'name'=> $product->name,
'price'=> $product->price,
'quantity'=> 1,
'image'=> $product->image_path,
];
}
session()->put('cart', $cart);
return response()->json([
'code'=> 200,
'message'=>'success'
],200);
}
public function showCart(){
$carts = session()->get('cart');
return view('products.cart',compact('carts'));
}
public function updateCart(Request $request){
if ($request->id && $request->quantity){
$carts = session()->get('cart');
$carts[$request->id]['quantity'] = $request->quantity;
session()->put('cart', $carts);
$carts = session()->get('cart');
$cartComponent = view('products.components.cart_component',compact('carts'))->render();
return response()->json(['cart_component' => $cartComponent, 'code'=> 200],200);
}
}
public function deleteCart(Request $request){
if ($request->id){
$carts = session()->get('cart');
unset($carts[$request->id]);
session()->put('cart', $carts);
$carts = session()->get('cart');
$cartComponent = view('products.components.cart_component',compact('carts'))->render();
return response()->json(['cart_component' => $cartComponent, 'code'=> 200],200);
}
}
}
- Vào cart_component.blade.php:
<div class="cart" data-url="{{route('deleteCart')}}">
<div class="container">
<div class="row">
<table class="table update_cart_url" data-url="{{route('updateCart')}}">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Ảnh sản phẩm</th>
<th scope="col">Tên sản phẩm</th>
<th scope="col">Giá sản phẩm</th>
<th scope="col">Số lượng</th>
<th scope="col">Tổng tiền</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@php
$total = 0;
@endphp
@foreach($carts as $id => $cartItem)
@php
$total += $cartItem['price'] * $cartItem['quantity'];
@endphp
<tr>
<th scope="row">{{ $id }}</th>
<td>
<img style="width: 100px; height: 100px;object-fit: contain"
src="{{ $cartItem['image'] }}" alt="">
</td>
<td>{{ $cartItem['name'] }}</td>
<td>{{ number_format($cartItem['price']) }} VND</td>
<td>
<input type="number" value="{{$cartItem['quantity']}}" min="1" class="quantity">
</td>
<td>{{ number_format($cartItem['price'] * $cartItem['quantity']) }} VND</td>
<td>
<a href="" data-id="{{$id}}" class="btn btn-primary cart_update">Cập nhật</a>
<a href="" data-id="{{$id}}"
class="btn btn-danger cart_delete">Xóa</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="col-md-12">
<h2>Tổng: {{ number_format($total) }} VND</h2>
</div>
</div>
</div>
</div>
- Vào cart.balde.php:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>show cart</title>
</head>
<body>
<div class="cart_wrapper">
@include('products.components.cart_component')
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
function cartUpdate(event) {
event.preventDefault();
let urlUpdateCart = $('.update_cart_url').data('url');
let id = $(this).data('id');
let quantity = $(this).parents('tr').find('input.quantity').val();
$.ajax({
type: "GET",
url: urlUpdateCart,
data: {id: id,quantity: quantity},
success: function (data) {
if(data.code == 200){
$('.cart_wrapper').html(data.cart_component);
alert('Cập nhật thành công');
}
},
error: function () {
}
});
}
function cartDelete(event){
event.preventDefault();
let urlDelete = $('.cart').data('url');
let id = $(this).data('id');
$.ajax({
type: "GET",
url: urlDelete,
data: {id: id},
success: function (data) {
if(data.code == 200){
$('.cart_wrapper').html(data.cart_component);
alert('Xóa thành công');
}
},
error: function () {
}
});
}
$(function () {
$(document).on('click','.cart_update',cartUpdate);
$(document).on('click','.cart_delete',cartDelete);
})
</script>
</body>
</html>
0 Nhận xét