The issue is that the findOrFail method in the itemCrudRepository class is throwing an exception when it cannot find the item with the negative ID. To handle this case and return a 404 response instead of a 500 response, you can catch the exception in the update method and throw a ModelNotFoundException with a custom message. Here's an updated version of the update method:
use Illuminate\Database\Eloquent\ModelNotFoundException;
public function update(int $id, array $data, UpdateItemRequest $request): Item
{
try {
$item = Item::findOrFail($id);
} catch (ModelNotFoundException $e) {
throw new ModelNotFoundException('Item not found', 404);
}
$item->title = $data['title'];
// ...
$item->save();
return $item;
}
With this change, when the findOrFail method throws an exception, it will be caught and a ModelNotFoundException with a 404 status code and a custom message will be thrown instead. This will result in a 404 response being returned to the client, as desired.