I am developing a Laravel API and am encountering issues with my ::put method. I can successfully create and retrieve a model, but when I attempt to delete or update, I receive Laravel's 404 page instead of the expected JSON response. If I use ::post to update the model, it works beautifully, but ::put should work as well and it doesn't.
In Postman, I first run the login route to authenticate the user. Then, I create a model successfully. However, when I attempt to update, it returns a 404 error instead of my expected JSON response of 'Badge not found'.
Here are the relevant parts of my BadgeController for update and destroy methods:
public function update(StoreBadgeRequest $request, Badge $badge): JsonResponse
{
// Check if the badge exists
if (!$badge->exists) {
return new JsonResponse([
'message' => 'Badge not found.'
], Response::HTTP_NOT_FOUND);
}
// Check if user has permission to edit badges
if (!auth()->user()->can('edit-badge')) {
return new JsonResponse([
'message' => 'You are not authorized to edit a badge.'
], Response::HTTP_FORBIDDEN);
}
$badge->update($request->validated());
return new JsonResponse([
'message' => 'Badge updated successfully.'
], Response::HTTP_OK);
}
public function destroy(Badge $badge): JsonResponse
{
// Check if user has permission to delete badges
if (!auth()->user()->can('delete-badge')) {
return new JsonResponse([
'message' => 'You are not authorized to delete a badge.'
], Response::HTTP_FORBIDDEN);
}
$badge->delete();
return new JsonResponse(
[
'message' => 'Badge deleted successfully.'
],
Response::HTTP_OK
);
}
API Endpoints:
Route::middleware('auth:api')->group(function () {
// Badges Routes
Route::put('/badges/{badge}', [BadgeController::class, 'update']);
Route::patch('/badges/{badge}', [BadgeController::class, 'update']);
Route::delete('/badges/{badge}', [BadgeController::class, 'destroy']);
});
POSTbut it should work when updating a model usingPUT.