diff --git a/app/Http/Controllers/CartController.php b/app/Http/Controllers/CartController.php new file mode 100644 index 0000000..4ab8f05 --- /dev/null +++ b/app/Http/Controllers/CartController.php @@ -0,0 +1,64 @@ + $product]); + } + + public function addToCart(Product $product) { + $user = Auth::user(); + $user->cart()->syncWithoutDetaching([$product->uuid]); + + return back(); + } + + public function removeFromCart(Product $product) { + $user = Auth::user(); + $user->cart()->detach($product); + return back(); + } + + /** + * Update the specified resource in storage. + * + * @param \Illuminate\Http\Request $request + * @param \App\Models\Product $product + * @return \Illuminate\Http\Response + */ + public function update(Request $request, Product $product) + { + $product->fill($request->all()); + $product->save(); + return redirect()->route("product.show", [ 'product' => $product])->with("message", "Product created successfully"); + } + + /** + * Remove the specified resource from storage. + * + * @param \App\Models\Product $product + * @return \Illuminate\Http\Response + */ + public function destroy(Product $product) + { + $product->delete(); + return redirect()->route("product.index"); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 4a0cff2..40bf04d 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -44,4 +44,8 @@ class User extends Authenticatable protected $casts = [ 'email_verified_at' => 'datetime', ]; + + public function cart() { + return $this->belongsToMany(Product::class, "cart_items", "userID", "productID"); + } } diff --git a/database/migrations/2021_11_19_060943_create_cart_items_table.php b/database/migrations/2021_11_19_060943_create_cart_items_table.php new file mode 100644 index 0000000..7f4f184 --- /dev/null +++ b/database/migrations/2021_11_19_060943_create_cart_items_table.php @@ -0,0 +1,32 @@ +id(); + $table->foreignUuid("userID")->references("uuid")->on("users"); + $table->foreignUuid("productID")->references("uuid")->on("products"); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('cart_items'); + } +} diff --git a/resources/views/product/view.blade.php b/resources/views/product/view.blade.php index 03d547e..fc8fa97 100644 --- a/resources/views/product/view.blade.php +++ b/resources/views/product/view.blade.php @@ -17,6 +17,15 @@ @method('DELETE') @csrf +
+ +