Home > Back-end >  how to make addToCart function in laravel
how to make addToCart function in laravel

Time:08-25

I am working on my laravel project. It is on Laravel 9. I need your help, please write to me add to cart logic, i know to search in google. I researched but did not find example for my code. Next i started editing but nothing comes. So, i need your help guys. I have table products in database which have title, price, description, image.

This is my shop.blade.php :

                        <div >
                            <a  href="http://localhost/e-commerce/public/shop/{{$product->id}}">{{$product->title}}</a>
                            <div >
                                <h5>{{$product->price}}$</h5><h6 ><del>{{$product->old_price}}$</del></h6>
                            </div>
                            <div >
                                <small ></small>
                                <small ></small>
                                <small ></small>
                                <small ></small>
                                <small ></small>
                                <small>(99)</small>
                            </div>
                            <a href="" >Add to Cart</a>
                        </div>
                    </div>

please help me

CodePudding user response:

You can create new table to save information, this table should contain product_id and user_id, when you press add_to_cart button you have to insert new row to the table, and by using laravel's belongsToMany relationship you can show products in cart page. It will be like this

App\Models\Product;
public function products_in_cart() {
  return $this->belongsToMany(User::class, "products_in_carts(this will be table name)", "product_id", "user_id");
}

CodePudding user response:

I suggest to do some google resarch. I would strongly suggest to use session (Redis) to storage, below some relevant code adatable to your needs, hope it helps. Sample source from: Laravel Shopping Cart

1- app/Models/Products.php

<?php
  
namespace App\Models;
   
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'price', 'description', 'image'
    ];
}

2-app/Http/Controllers/ProductController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $products = Product::all();
        return view('products', compact('products'));
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function cart()
    {
        return view('cart');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function addToCart($id)
    {
        $product = Product::findOrFail($id);
          
        $cart = session()->get('cart', []);
  
        if(isset($cart[$id])) {
            $cart[$id]['quantity']  ;
        } else {
            $cart[$id] = [
                "name" => $product->name,
                "quantity" => 1,
                "price" => $product->price,
                "image" => $product->image
            ];
        }
          
        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function update(Request $request)
    {
        if($request->id && $request->quantity){
            $cart = session()->get('cart');
            $cart[$request->id]["quantity"] = $request->quantity;
            session()->put('cart', $cart);
            session()->flash('success', 'Cart updated successfully');
        }
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function remove(Request $request)
    {
        if($request->id) {
            $cart = session()->get('cart');
            if(isset($cart[$request->id])) {
                unset($cart[$request->id]);
                session()->put('cart', $cart);
            }
            session()->flash('success', 'Product removed successfully');
        }
    }
}

3-resources/views/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Add To Cart Function - ItSolutionStuff.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  
    <link href="{{ asset('css/style.css') }}" rel="stylesheet">
</head>
<body>
  
<div >
    <div >
        <div >
            <div >
                <button type="button"  data-toggle="dropdown">
                    <i  aria-hidden="true"></i> Cart <span >{{ count((array) session('cart')) }}</span>
                </button>
                <div >
                    <div >
                        <div >
                            <i  aria-hidden="true"></i> <span >{{ count((array) session('cart')) }}</span>
                        </div>
                        @php $total = 0 @endphp
                        @foreach((array) session('cart') as $id => $details)
                            @php $total  = $details['price'] * $details['quantity'] @endphp
                        @endforeach
                        <div >
                            <p>Total: <span >$ {{ $total }}</span></p>
                        </div>
                    </div>
                    @if(session('cart'))
                        @foreach(session('cart') as $id => $details)
                            <div >
                                <div >
                                    <img src="{{ $details['image'] }}" />
                                </div>
                                <div >
                                    <p>{{ $details['name'] }}</p>
                                    <span > ${{ $details['price'] }}</span> <span > Quantity:{{ $details['quantity'] }}</span>
                                </div>
                            </div>
                        @endforeach
                    @endif
                    <div >
                        <div >
                            <a href="{{ route('cart') }}" >View all</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
  
<br/>
<div >
  
    @if(session('success'))
        <div >
          {{ session('success') }}
        </div> 
    @endif
  
    @yield('content')
</div>
  
@yield('scripts')
     
</body>
</html>

4-resources/views/products.blade.php

@extends('layout')
   
@section('content')
    
<div >
    @foreach($products as $product)
        <div >
            <div >
                <img src="{{ $product->image }}" alt="">
                <div >
                    <h4>{{ $product->name }}</h4>
                    <p>{{ $product->description }}</p>
                    <p><strong>Price: </strong> {{ $product->price }}$</p>
                    <p ><a href="{{ route('add.to.cart', $product->id) }}"  role="button">Add to cart</a> </p>
                </div>
            </div>
        </div>
    @endforeach
</div>
    
@endsection

5-resources/views/cart.blade.php

@extends('layout')
  
@section('content')
<table id="cart" >
    <thead>
        <tr>
            <th style="width:50%">Product</th>
            <th style="width:10%">Price</th>
            <th style="width:8%">Quantity</th>
            <th style="width:22%" >Subtotal</th>
            <th style="width:10%"></th>
        </tr>
    </thead>
    <tbody>
        @php $total = 0 @endphp
        @if(session('cart'))
            @foreach(session('cart') as $id => $details)
                @php $total  = $details['price'] * $details['quantity'] @endphp
                <tr data-id="{{ $id }}">
                    <td data-th="Product">
                        <div >
                            <div ><img src="{{ $details['image'] }}" width="100" height="100" /></div>
                            <div >
                                <h4 >{{ $details['name'] }}</h4>
                            </div>
                        </div>
                    </td>
                    <td data-th="Price">${{ $details['price'] }}</td>
                    <td data-th="Quantity">
                        <input type="number" value="{{ $details['quantity'] }}"  />
                    </td>
                    <td data-th="Subtotal" >${{ $details['price'] * $details['quantity'] }}</td>
                    <td  data-th="">
                        <button ><i ></i></button>
                    </td>
                </tr>
            @endforeach
        @endif
    </tbody>
    <tfoot>
        <tr>
            <td colspan="5" ><h3><strong>Total ${{ $total }}</strong></h3></td>
        </tr>
        <tr>
            <td colspan="5" >
                <a href="{{ url('/') }}" ><i ></i> Continue Shopping</a>
                <button >Checkout</button>
            </td>
        </tr>
    </tfoot>
</table>
@endsection
  
@section('scripts')
<script type="text/javascript">
  
    $(".update-cart").change(function (e) {
        e.preventDefault();
  
        var ele = $(this);
  
        $.ajax({
            url: '{{ route('update.cart') }}',
            method: "patch",
            data: {
                _token: '{{ csrf_token() }}', 
                id: ele.parents("tr").attr("data-id"), 
                quantity: ele.parents("tr").find(".quantity").val()
            },
            success: function (response) {
               window.location.reload();
            }
        });
    });
  
    $(".remove-from-cart").click(function (e) {
        e.preventDefault();
  
        var ele = $(this);
  
        if(confirm("Are you sure want to remove?")) {
            $.ajax({
                url: '{{ route('remove.from.cart') }}',
                method: "DELETE",
                data: {
                    _token: '{{ csrf_token() }}', 
                    id: ele.parents("tr").attr("data-id")
                },
                success: function (response) {
                    window.location.reload();
                }
            });
        }
    });
  
</script>
@endsection

6-public/css/style.css

.thumbnail {
    position: relative;
    padding: 0px;
    margin-bottom: 20px;
}
.thumbnail img {
    width: 80%;
}
.thumbnail .caption{
    margin: 7px;
}
.main-section{
    background-color: #F8F8F8;
}
.dropdown{
    float:right;
    padding-right: 30px;
}
.btn{
    border:0px;
    margin:10px 0px;
    box-shadow:none !important;
}
.dropdown .dropdown-menu{
    padding:20px;
    top:30px !important;
    width:350px !important;
    left:-110px !important;
    box-shadow:0px 5px 30px black;
}
.total-header-section{
    border-bottom:1px solid #d2d2d2;
}
.total-section p{
    margin-bottom:20px;
}
.cart-detail{
    padding:15px 0px;
}
.cart-detail-img img{
    width:100%;
    height:100%;
    padding-left:15px;
}
.cart-detail-product p{
    margin:0px;
    color:#000;
    font-weight:500;
}
.cart-detail .price{
    font-size:12px;
    margin-right:10px;
    font-weight:500;
}
.cart-detail .count{
    color:#C2C2DC;
}
.checkout{
    border-top:1px solid #d2d2d2;
    padding-top: 15px;
}
.checkout .btn-primary{
    border-radius:50px;
    height:50px;
}
.dropdown-menu:before{
    content: " ";
    position:absolute;
    top:-20px;
    right:50px;
    border:10px solid transparent;
    border-bottom-color:#fff;
}
  • Related