From fd0c0a7e5d19663a2ccc0dff327098021a82e65b Mon Sep 17 00:00:00 2001 From: BackwardsUser Date: Tue, 25 Mar 2025 01:54:06 -0400 Subject: [PATCH] setup API routes --- routes/api.php | 118 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/routes/api.php b/routes/api.php index e69de29..57d2f34 100644 --- a/routes/api.php +++ b/routes/api.php @@ -0,0 +1,118 @@ +all(), [ + 'name' => 'required|string|max:255', + 'description' => 'required|string', + 'cost' => 'required|numeric|min:0', + ]); + + if ($validator->fails()) { + return response()->json([ + 'status' => 'Missing or Invalid request body data', + ], 422); + } + + // Validated input + $data = $validator->validated(); + + $item = new Inventory; + $item->name = $data["name"]; + $item->description = $data["description"]; + $item->cost = $data["cost"]; + $item->save(); + + return response()->json([ + 'status' => 'Item inserted successfully' + ]); +})->middleware('auth:sanctum')->fallback(); + +Route::put('/', function(Request $request) { + $items = $request->all(); + + if (!is_array($items)) { + return response()->json(['status' => 'Invalid request format: Expected an array'], 422); + } + + foreach ($items as $index => $item) { + $validator = Validator::make($item, [ + 'name' => 'required|string|max:255', + 'description' => 'required|string', + 'cost' => 'required|numeric|min:0', + ]); + + if ($validator->fails()) { + return response()->json([ + 'status' => "Invalid item at index $index", + 'errors' => $validator->errors() + ], 422); + } + } + + Inventory::query()->delete(); + + foreach ($items as $item) { + Inventory::create([ + 'name' => $item['name'], + 'description' => $item['description'], + 'cost' => $item['cost'], + ]); + } + + return response()->json(['status' => 'Collection Replaced']); +})->middleware('auth:sanctum'); + +Route::delete('/', function() { + Inventory::query()->delete(); +}); + + + +Route::get("/{id}", function ($id) { + return Inventory::where('id', $id)->get(); +}); + +Route::put('/{id}', function(Request $request, $id) { + $item = $request->all(); + + $validator = Validator::make($item, [ + 'name' => 'required|string|max:255', + 'description' => 'required|string', + 'cost' => 'required|numeric|min:0', + ]); + + if ($validator->fails()) { + return response()->json([ + 'status' => "Invalid item", + 'errors' => $validator->errors() + ], 422); + } + + $inventory = Inventory::find($id); + if (!$inventory) { + return response()->json(['status' => 'Item not found'], 404); + } + + $inventory->update([ + 'name' => $item['name'], + 'description' => $item['description'], + 'cost' => $item['cost'], + ]); + + return response()->json(['status' => 'Item Updated']); +})->middleware('auth:sanctum'); + + +Route::delete('/{id}', function($id) { + Inventory::where('id', $id)->query()->delete(); +});