If the category already has an image skip the validation for the image and if it doesn't already have a category image execute the validation.
Apr 16, 2024
10
Level 21
don't want to update a older category image ?
my edit form data from the browser.
<form action="http://restaurent-app.test/admin/categories/18" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_token" value="WumE6IC65giVihLTOl4lIlQzPa83VmHQIfd9GiIt" autocomplete="off"> <input type="hidden" name="_method" value="PUT">
<div class="space-y-3">
<div class="space-y-2">
<label class="font-mono">Category Name</label>
<input class="px-3 block w-full border-gray-200 rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none" value="Upton Mayer" name="name" type="text">
</div>
<div class="space-y-2">
<label class="font-mono">Image</label>
<input class="px-3 block w-full border-gray-200 rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none border py-2" value="tim-mossholder-WE_Kv_ZB1l0-unsplash.jpg" name="image" type="file">
<p class="text-red-500 text-sm">
The image field is required.
</p>
</div>
<div class="space-y-2">
<label class="font-mono">Description</label>
<textarea class="w-full px-1 rounded border border-gray-200" cols="5" rows="3" name="description">Fuga Voluptatem Te</textarea>
</div>
</div>
<div class="py-3 flex justify-between items-center md:justify-end gap-10">
<a class="px-3 py-2 rounded-md shadow-md hover:text-white hover:bg-yellow-500 border border-yellow-400" href="http://restaurent-app.test/admin/categories">
Cancel
</a>
<button type="submit" class="bg-blue-600 text-white px-3 py-2 rounded-md shadow-md hover:bg-blue-700">
Update
</button> </div>
</form>
my controller update method
public function update(CategoryRequest $request, Category $category)
{
$imageName = $category->image; // Default to the current image name
// Check if a new image was uploaded
$image = $request->file('image');
if ($image) {
$imageName = $image->getClientOriginalName();
$image->storeAs('public/categories', $imageName);
// Delete the old image if it exists
if ($category->image) {
unlink('public/categories/' . $category->image);
}
}
// Update the category
$category->update([
'name' => $request->name,
'description' => $request->description,
'image' => $imageName,
]);
session()->flash('msg', 'Category updated successfully.');
return redirect()->route('categories.index');
}
and I want to achieve the functionality when editing the category if user is not sending any images then what to do ? In other words he thinks older image was perfect so don't need to update that image.
As I have added a required validation for the image also , due to that required validation it asking me image that it is required how to handle it?
Please or to participate in this conversation.