Added Delete PRODUCT with Items and dettaching from users

This commit is contained in:
Bruno F. Fontes 2018-09-17 00:51:41 -03:00
parent 707dd1654a
commit c38744e392
4 changed files with 21 additions and 27 deletions

View File

@ -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);
}
}

View File

@ -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)

View File

@ -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();
}
}

View File

@ -16,7 +16,7 @@
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<form action="/delete" method="POST">
<form action="/product" method="POST">
@method('DELETE')
{{ csrf_field() }}
<input type="hidden" name="product" value="{{$product->id}}">