I’m currently working on a Laravel project where I need to update categories, including handling image uploads and validation. The store method works perfectly, but I’m encountering issues with the update method.
Here’s a brief overview of what I’m trying to achieve:
Controller: KategorilerController
Function: update
The goal is to update a category’s name and image. However, the update process isn’t working as expected. I’m not receiving any errors, but the data isn’t being updated in the database.
Here is a snippet of my update method:
Kategoriler //model
class Kategoriler extends Model
{
use HasFactory;
protected $table = 'kategorilers';
protected $fillable = [
'kategori_adi',
'resim',
'aktif'
];
protected $hidden = [
'silindi',
'created_at',
'updated_at',
];
public function urunler()
{
return $this->hasMany(Urunler::class, 'kategori_id');
}
}
KategoriController.php
public function update(Request $request, $id)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$category = Category::find($id);
if (!$category) {
return response()->json(['error' => 'Category not found'], 404);
}
$category->name = $validatedData['name'];
if ($request->hasFile('image')) {
// Handle the image upload
$imageName = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $imageName);
$category->image = $imageName;
}
$category->save();
return response()->json(['success' => 'Category updated successfully']);
}
Postman Response
{
"message": "validation.required",
"errors": {
"kategori_adi": [
"validation.required"
]
}
}
I have double-checked the following:
The $id is correct and corresponds to an existing category.
The validation is passing without issues.
The file is being uploaded correctly when present.
Despite these checks, the data is not being updated in the database. Could anyone help me identify what might be going wrong or suggest any improvements to the update method?
Thank you in advance for your assistance!
I have tried several things to resolve the issue:
Verified that the $id provided corresponds to an existing category in the database.
Checked the validation rules to ensure they are correct and that the request data is passing validation.
Confirmed that the image file is being uploaded correctly when present and is stored in the public/images directory.
Added some debug statements to check whether the code is reaching the point where the category is being updated.
I was expecting the update method to update the category’s name and image in the database. Specifically, if the image is uploaded, I expected it to be saved in the public/images directory, and the database record to be updated with the new image name and the new category name. After the update, I expected the response to indicate that the category was updated successfully.