diff --git a/app/Http/Controllers/ItemController.php b/app/Http/Controllers/ItemController.php index b9f94c3..babbf9b 100644 --- a/app/Http/Controllers/ItemController.php +++ b/app/Http/Controllers/ItemController.php @@ -58,17 +58,11 @@ class ItemController extends Controller public function delete(Request $request) { $request->validate(['item' => 'required']); - $item = User::find(\Auth::id()) + $item = User::findOrFail(\Auth::id()) ->items()->with('users')->find(request('item')); $product = $item->product_id; - //Detach users from this item - foreach ($item->users as $user) { - User::findOrFail($user->id)->items()->detach($item->id); - } - - //Delete item - $item->delete(); + Item::deleteAndDetach($item); return redirect('product/' . $product); } } \ No newline at end of file diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index c0f0328..22cb29e 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -2,9 +2,10 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; -use \App\Product; +use \App\Item; use \App\User; +use \App\Product; +use Illuminate\Http\Request; class ProductController extends Controller { @@ -33,20 +34,18 @@ class ProductController extends Controller */ public function delete(Request $request) { - //TODO: Delete all items with all users for the product $request->validate(['product' => 'required']); - $item = User::findOrFail(\Auth::id()) - ->items()->with('users')->find(request('item')); - $product = $item->product_id; + $product = User::findOrFail(\Auth::id()) + ->products()->with('items')->find(request('product')); //Detach users from this item - foreach ($item->users as $user) { - User::findOrFail($user->id)->items()->detach($item->id); + foreach ($product->items as $item) { + Item::deleteAndDetach($item); } - //Delete item - $item->delete(); - return redirect('product/' . $product); + //Delete product + $product->delete(); + return redirect('product'); } public function patch(Request $request) diff --git a/app/Item.php b/app/Item.php index 23dfbb4..b10da1f 100644 --- a/app/Item.php +++ b/app/Item.php @@ -18,13 +18,14 @@ class Item extends Model return $this->belongsToMany(User::class); } - public function free($product_id, $user_id) + public static function deleteAndDetach($item) { - return $query->where([ - ['user_id', $user_id], - ['product_id', $product_id], - ['used_by', ''], - ]); - } + //Detach users from this item + foreach ($item->users as $user) { + User::findOrFail($user->id)->items()->detach($item->id); + } + //Delete item + $item->delete(); + } } diff --git a/resources/views/product/deleteButton.blade.php b/resources/views/product/deleteButton.blade.php index 7886f83..3ec5681 100644 --- a/resources/views/product/deleteButton.blade.php +++ b/resources/views/product/deleteButton.blade.php @@ -16,7 +16,7 @@