@@ -25,11 +25,16 @@ class AccessoryCheckoutController extends Controller
2525 public function create ($ accessoryId )
2626 {
2727 // Check if the accessory exists
28- if (is_null ($ accessory = Accessory::find ($ accessoryId ))) {
28+ if (is_null ($ accessory = Accessory::withCount ( ' users as users_count ' )-> find ($ accessoryId ))) {
2929 // Redirect to the accessory management page with error
3030 return redirect ()->route ('accessories.index ' )->with ('error ' , trans ('admin/accessories/message.not_found ' ));
3131 }
3232
33+ // Make sure there is at least one available to checkout
34+ if ($ accessory ->numRemaining () <= 0 ){
35+ return redirect ()->route ('accessories.index ' )->with ('error ' , trans ('admin/accessories/message.checkout.unavailable ' ));
36+ }
37+
3338 if ($ accessory ->category ) {
3439 $ this ->authorize ('checkout ' , $ accessory );
3540
@@ -55,17 +60,23 @@ public function create($accessoryId)
5560 public function store (Request $ request , $ accessoryId )
5661 {
5762 // Check if the accessory exists
58- if (is_null ($ accessory = Accessory::find ($ accessoryId ))) {
63+ if (is_null ($ accessory = Accessory::withCount ( ' users as users_count ' )-> find ($ accessoryId ))) {
5964 // Redirect to the accessory management page with error
6065 return redirect ()->route ('accessories.index ' )->with ('error ' , trans ('admin/accessories/message.user_not_found ' ));
6166 }
6267
6368 $ this ->authorize ('checkout ' , $ accessory );
6469
65- if (! $ user = User::find ($ request ->input ('assigned_to ' ))) {
70+ if (!$ user = User::find ($ request ->input ('assigned_to ' ))) {
6671 return redirect ()->route ('accessories.checkout.show ' , $ accessory ->id )->with ('error ' , trans ('admin/accessories/message.checkout.user_does_not_exist ' ));
6772 }
6873
74+ // Make sure there is at least one available to checkout
75+ if ($ accessory ->numRemaining () <= 0 ){
76+ return redirect ()->route ('accessories.index ' )->with ('error ' , trans ('admin/accessories/message.checkout.unavailable ' ));
77+ }
78+
79+
6980 // Update the accessory data
7081 $ accessory ->assigned_to = e ($ request ->input ('assigned_to ' ));
7182
@@ -77,15 +88,6 @@ public function store(Request $request, $accessoryId)
7788 'note ' => $ request ->input ('note ' ),
7889 ]);
7990
80- $ available = new Accessory ();
81-
82-
83-
84- if ($ available ->numRemaining ()<=0 ){
85-
86- return redirect ()->route ('accessories.index ' )->with ('error ' , trans ('admin/accessories/message.checkout.unavailable ' ));
87- }
88-
8991 DB ::table ('accessories_users ' )->where ('assigned_to ' , '= ' , $ accessory ->assigned_to )->where ('accessory_id ' , '= ' , $ accessory ->id )->first ();
9092
9193 event (new CheckoutableCheckedOut ($ accessory , $ user , Auth::user (), $ request ->input ('note ' )));
0 commit comments