this had been my code :// Update a blog
public function update(Request $request, Blog $blog)
{ Log::info('Received data:', $request->all());
// Ensure the authenticated user is an admin
if ($request->user()->role !== 'admin') {
return response()->json(['message' => 'Unauthorized'], 403);
}
// Validate the request data
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
'media' => 'sometimes|file|mimes:jpg,jpeg,png,gif,bmp,svg,webp|max:20480', // 20MB size limit
]);
// Handle media file if provided
if ($request->hasFile('media')) {
// Delete the old media file from storage if it exists
if ($blog->media && Storage::exists('public/media/' . $blog->media)) {
Storage::delete('public/media/' . $blog->media);
}
// Process and store the new media file
$filenameWithExt = $request->file('media')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('media')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->file('media')->storeAs('public/media', $fileNameToStore);
$blog->media = $fileNameToStore;
}
// Update the blog with validated (and manually set) data
$blog->title = $request->title;
$blog->content = $request->content;
$blog->save(); // Manually saving the model after setting attributes
Log::info('Blog Data after:', $blog->toArray());
return response()->json($blog, 200);
}
} after changing put request in api.php to a post, it recieves my data in the backend just fine, opposed to when it was set to a put. What could be the problem?
I was initially trying to work with a put request since Im trying to update a blog using a modal to fill and on submit it should edit the contents, but I kept getting a 422 error concerning validation rules, saying title and content is required even though they re being successfully appended in the frontend, but somehow not received on the backend. ( checked laravel logs)