Skip to content

Commit

Permalink
Cart feature: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Slymee committed Mar 19, 2024
1 parent 0d52a11 commit c921d62
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 79 deletions.
28 changes: 17 additions & 11 deletions app/Http/Controllers/CartController.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<?php
declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\CartItemsRequest;
use App\Models\Cart;
use App\Repositories\CartRepository;
use App\Repositories\Interfaces\CartRepositoryInterface;
use Illuminate\Http\Request;

Expand All @@ -18,9 +17,10 @@ public function __construct(CartRepositoryInterface $cartRepository)
/**
* Display a listing of the resource.
*/
public function index()
public function index(string $userId)
{
//
$cartItems = $this->cartRepository->showCartItems($userId);
return view('userend.cart-items', compact('cartItems'));
}

/**
Expand All @@ -34,12 +34,12 @@ public function create()
/**
* Store a newly created resource in storage.
*/
public function store(CartItemsRequest $request)
public function store(CartItemsRequest $request): \Illuminate\Http\RedirectResponse
{
$this->cartRepository->store($request->all());

return redirect()->back()->with('message', 'Product added to cart.');

if ($this->cartRepository->store($request->all())){
return redirect()->back()->with('message', 'Product Added to Cart.');
}
return redirect()->back()->with('message', 'Product failed to add!');
}

/**
Expand Down Expand Up @@ -69,8 +69,14 @@ public function update(Request $request, Cart $cart)
/**
* Remove the specified resource from storage.
*/
public function destroy(Cart $cart)
public function destroy(Request $request)
{
//
$validated = $request->validate([
'cart_id' => 'required'
]);
if ($this->cartRepository->removeFromCart($validated['cart_id'])){
return redirect()->back()->with('message', 'Removed from cart.');
}
return redirect()->back()->with('message', 'Could not remove.');
}
}
13 changes: 10 additions & 3 deletions app/Models/Cart.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,22 @@
class Cart extends Model
{
use HasFactory;

protected $table = 'carts';

protected $fillable = [
'buyer_id',
'product_id',
'quantity',
'amount',
];

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

public function product()
{
return $this->belongsToMany(Product::class, 'cart_products')->withPivot('quantity');
return $this->belongsTo(Product::class);
}
}
2 changes: 1 addition & 1 deletion app/Models/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function comments(): MorphMany

public function carts()
{
return $this->belongsToMany(CartItems::class)->withPivot('quantity');
return $this->hasMany(Cart::class);
}

public function getRouteKeyName(): string
Expand Down
74 changes: 57 additions & 17 deletions app/Repositories/CartRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,73 @@

use App\Models\Cart;
use App\Repositories\Interfaces\CartRepositoryInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class CartRepository implements CartRepositoryInterface
{
public function store(array $data)
/**
* @param string $userId
* @return mixed
*/
public function showCartItems(string $userId)
{
// TODO: Implement showCartItems() method.
return Cart::where('buyer_id', $userId)
->with('product')
->paginate(10);
}

/**
* @param array $data
* @return bool
*/
public function store(array $data): bool
{
// TODO: Implement store() method.
try {
$cart = Cart::where('buyer_id', $data['buyer_id'])->first();

if (!$cart){
$cart = Cart::create(['buyer_id' => $data['buyer_id']]);
}
$cart = Cart::where('buyer_id', $data['buyer_id'])
->where('product_id', $data['product_id'])
->first();

if ($cart->products->contains($data['product_id'])) {
$existingProduct = $cart->products->find($data['product_id']);
$cart->products()
->updateExistingPivot($data['product_id'], ['quantity' => $existingProduct->pivot->quantity + $data['quantity']]);
} else {
$cart->products()->attach($data['product_id'], ['quantity' => $data['quantity']]);
if ($cart){
$cart->quantity += $data['quantity'];
$cart->amount = $cart->quantity * $data['price'];
$cart->save();
}else{
Cart::create([
'buyer_id' => $data['buyer_id'],
'product_id' => $data['product_id'],
'quantity' => $data['quantity'],
'amount' => ($data['quantity']*$data['price']),
]);
}

return true;
}catch (\Exception $e) {
Log::error('Caught Exception: ' . $e->getMessage());
Log::error('Exception Details: ' . $e);
throw $e;
}catch (\Exception $e){
DB::rollBack();
Log::error('Caught Exception: ' . $e->getMessage());
Log::error('Exception Details: ' . $e);
return false;
}
}

/**
* @param string $cartId
* @return bool
*/
public function removeFromCart(string $cartId): bool
{
try {
if (Cart::find($cartId)->delete()){
return true;
}
return false;
}catch (\Exception $e){
DB::rollBack();
Log::error('Caught Exception: ' . $e->getMessage());
Log::error('Exception Details: ' . $e);
return false;
}
}
}
3 changes: 3 additions & 0 deletions app/Repositories/Interfaces/CartRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@

interface CartRepositoryInterface
{
public function showCartItems(string $userId);
public function store(array $data);

public function removeFromCart(string $cartId);
}
35 changes: 0 additions & 35 deletions database/migrations/2024_03_18_080811_create_carts_table.php

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,23 @@
*/
public function up(): void
{
Schema::create('cart_products', function (Blueprint $table) {
Schema::create('carts', function (Blueprint $table) {
$table->id();

$table->unsignedBigInteger('cart_id');
$table->foreign('cart_id')
->references('id')
->on('carts')
$table->unsignedBigInteger('buyer_id');
$table->foreign('buyer_id')->references('id')
->on('users')
->onUpdate('cascade')
->onDelete('cascade');

$table->unsignedBigInteger('product_id');
$table->foreign('product_id')
->references('id')
$table->foreign('product_id')->references('id')
->on('products')
->onUpdate('cascade')
->onDelete('cascade');

$table->tinyInteger('quantity');
$table->integer('amount');

$table->timestamps();
});
Expand All @@ -39,6 +38,6 @@ public function up(): void
*/
public function down(): void
{
Schema::dropIfExists('cart_products');
Schema::dropIfExists('carts');
}
};
9 changes: 9 additions & 0 deletions resources/css/cart-items.css
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@
justify-content: space-between;
}

.cart-item-img>img{
width: 100px;
height: 80px;
}
.cart-item-info{
width: 70%;
font-size: 110%;
}

*::-webkit-scrollbar {
width: 8px; /* Adjust this value to make the scrollbar thinner or thicker */
}
Expand Down
21 changes: 17 additions & 4 deletions resources/views/userend/cart-items.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,23 @@
<section class="banner-container">
<div class="checkout-container">
<div class="item-container">
<div class="cart-item-banner">
<div class="cart-item-img"></div>
<div class="cart-item-info"></div>
</div>
@foreach($cartItems as $cartItem)
<div class="cart-item-banner">
<div class="cart-item-img"><img src="{{ asset('storage/'.$cartItem->product->image_path) }}" alt=""></div>
<div class="cart-item-info">
<a href=""><div class="">{{ $cartItem->product->product_title }}</div></a>
<div class="">Amount: {{ $cartItem->amount }}</div>
<div class="">Quantity: {{ $cartItem->quantity }}</div>
</div>
<div class="cart-item-util">
<form method="POST" action="{{ route('remove-from-cart') }}">
@csrf
<input type="hidden" name="cart_id" value="{{ $cartItem->id }}">
<input type="submit" value="Remove">
</form>
</div>
</div>
@endforeach
</div>
<div class="utility-container">dfghdfgfdg</div>
</div>
Expand Down

0 comments on commit c921d62

Please sign in to comment.