You first need to authenticate via Postman.
Laravel PUT request to API via Postman not working.
routes/api.php
// UserController Routes (Requires authentication)
Route::middleware('auth:sanctum')->controller(UserController::class)->group(function () {
Route::get('/profile', 'getProfile');
Route::put('/profile', 'updateProfile');
});
Controllers/UserController.php
/**
* Update the authenticated user's profile information.
*
* @param UpdateProfileRequest $request
* @return JsonResponse
*/
public function updateProfile(UpdateProfileRequest $request): JsonResponse
{
try {
// Get the authenticated user
$user = $request->user();
// Handle the Avatar upload
if ($request->hasFile('avatar')) {
// If there is an existing avatar, delete it from storage
if ($user->avatar) {
$existing_avatar = str_replace('/storage/', '', $user->avatar);
Storage::disk('public')->delete($existing_avatar);
}
// Store the new avatar
$avatar = $request->file('avatar')->store('user_avatars', 'public');
$user->avatar = Storage::url($avatar);
}
// Update the user's profile information, including the avatar if it was uploaded
$user->update($request->validated());
// Return the updated user data
return response()->json([
'success' => true,
'message' => 'Profile updated successfully.',
'data' => $user,
]);
} catch (Throwable $e) {
// Log the error message
Log::error('Error updating user profile: ' . $e->getMessage());
// Return an error response
return response()->json([
'success' => false,
'message' => 'An error occurred while updating the profile.',
], 500);
}
}
I'm currently testing this endpoint with Postman form-data. On sending the request, the fields are not being updated. So I tried logging the request fields but it returned an empty array. After noticing that, I switched the method to a POST method both on Postman and in the api.php file. To my surprise, it returned the fields. What could be the cause of this behavior. Please am I doing something wrong here.
PS: before returning the request, I removed ": JsonResponse" type hint from the updateProfile method.
Route::put('/profile', 'updateProfile');`
You can fake it, send a POST request to api/profile and add one more attribute _method which will be set to PUT.
Edit, not fake it, but this is actually how the framework works.
Please or to participate in this conversation.