Current File : /home/tradevaly/www/app/Http/Controllers/User/CartController.php
<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\User;
use App\Models\Product;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index(){
        $carts = Cart::where('user_id',auth()->id())->get();
        return view('user.pages.product.cart',compact('carts'));
        
    }
    public Function store(Request $request)
    {
        $iscart = Cart::where('user_id',auth()->id())->where('product_id',$request->product_id)->count();
        
        if(auth()->user()->type == "seller"){
            Toastr::warning('Warning!','You are a Seller! You cant buy Product');
            return back();
        }else{
            if($iscart>0)
            {
                $cart = Cart::where('user_id',auth()->id())->where('product_id',$request->product_id)->latest()->first();
                $cart->quantity = $cart->quantity + $request->quantity;
                $cart->save();
                Toastr::success('Success!','Product add cart successfully!');
                return back();
            }
            else{
            $cart = new Cart();
            $cart->product_id = $request->product_id;
            $cart->user_id = auth()->id();
            $cart->quantity = $request->quantity;
            $cart->save();
            Toastr::success('Success!','Product add cart successfully!');
            return back();
            }
        }
    }
    public function update(Request $request,$id)
    {
        $cart = Cart::where('user_id',auth()->id())->where('id',$id)->firstOrFail();
        $cart->quantity =$request->quantity;
        $cart->save();
        Toastr::success('Success!','cart update successfully!');
        return back();
    }
    public function delete($id)
    {
        $cart = Cart::where('id',$id)->where('user_id',auth()->id())->latest()->first();
        $cart->delete();
        Toastr::success('Success!','Product removed from cart!');
        return back();
    }
}